Skip to content

Instantly share code, notes, and snippets.

@loopj
Created January 7, 2012 00:32
Show Gist options
  • Save loopj/1573243 to your computer and use it in GitHub Desktop.
Save loopj/1573243 to your computer and use it in GitHub Desktop.
Rough script for counting how many events per second you are doing, with rolling average
# Usage:
#
# timer = AverageTimer.new
# my_loop do
# # Track an avent
# timer.event
#
# # Print the events per second (averaged over 5 seconds)
# puts timer.events_per_second(5)
#
# # Print the events per second (averaged over 30 seconds)
# puts timer.events_per_second(30)
# end
class AverageTimer
def initialize(opts={})
@resolution = opts[:resolution] || 5
@keep_averages = opts[:keep_averages] || 10
@count = 0
@averages = []
end
def event
# Start the timer if this is the first event
@start_time = Time.now if @start_time.nil?
if @start_time + @resolution < Time.now
average = @count / @resolution.to_f
@count = 0
@start_time = Time.now
@averages << average
@averages.last(@keep_averages)
end
@count += 1
end
def events_per_second(average_period=5)
last = @averages.last
return nil if last.nil?
return last/@resolution if average_period < @resolution
num_avgs = [@averages.length, (average_period/@resolution.to_f).ceil].min
@averages.last(num_avgs).instance_eval { reduce(:+) / size.to_f } / @resolution
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment