0

特定の時間スケールの一連の数値を返すレポートを生成する必要があります。

たとえば、特定の月の視聴時間を返す必要があります。これが私が現在実行しているものです

presentation = Presentation.find(1)
presentation.video.stats.minutes_by_date(Date.new(2012,6,1),Date.new(2012,6,30))


def self.by_date(start_date,end_date)
    vals = Array.new
    (start_date..end_date).map { |date|
      yesterdays_stat = daily_watched(date.yesterday)
      todays_stat = daily_watched(date)

      if todays_stat > 0
        if yesterdays_stat > 0
          difference = todays_stat - yesterdays_stat
        else
          difference = todays_stat
        end
        watched_in_meg = (difference / 1024).round(2)
        vals.push (watched_in_meg / first.video.meg_per_minute).round(2)
      else
        vals.push 0
      end
    }
    vals
  end

  def self.daily_watched(date)
    # get the total bytes for the from both flash and mp4
    total_bytes = 0
    bytes = where(["DATE(generated_date) = ?", date]).group("kbytes")
    .order('generated_date')
    bytes.each do |byte|
      total_bytes += byte.kbytes
    end
    total_bytes
    # Get the bytes of both flash and mp4
  end

出力は次のようになります。

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 0]

問題は、これはプレゼンテーションごとに 30 回実行する必要があり、10 から 500 のプレゼンテーションがあることです。

これをより効率的にする方法はありますか?

4

2 に答える 2

1

単一のクエリですべての日付の統計を取得することから始めて、配列を 1 回パスして差を計算できます。

クエリは大まかに次のようになります。

result = Thing.select("DATE(generated_date) as date, SUM(kbytes) as sum_kbytes").group("DATE(generated_date)").where...
result.each{|i| puts "#{i.date} #{i.sum_kbytes}"}
于 2012-07-05T19:29:33.517 に答える
0

各日の各プレゼンテーションの差分 var を事前に計算します。次に、この関数で事前計算されたテーブルから読み取ります。

于 2012-07-05T18:24:47.437 に答える