Skip to content

Instantly share code, notes, and snippets.

@willf
Forked from mojombo/stats.rb
Created September 16, 2009 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willf/187846 to your computer and use it in GitHub Desktop.
Save willf/187846 to your computer and use it in GitHub Desktop.
one pass through records (for mean and variance); annoyingly proper definition of median
# Run the given block +num+ times and then print out the mean, median, min,
# max, and stddev of the run. For example:
#
# irb> stats(10) { sleep(rand / 100) }
# mean: 5.99ms
# median: 6.76ms
# min: 1.49ms
# max: 9.28ms
# stddev: 2.54ms
def stats(num)
records = []
num.times do
t0 = Time.now
yield
records << (Time.new-t0)
end
srecords = records.sort
num = records.size
n, mean, m2 = records.inject([0,0.0,0.0]) do
|acc, r|
n = acc[0]+1
delta = r-acc[1]
mean = acc[1] + (delta/n)
m2 = acc[2] + (delta * (r-mean))
[n, mean, m2]
end
var = m2/n
puts "mean: %1.2fms" % (mean * 1000)
puts "median: %1.2fms" % ((num % 2 == 1) ? (srecords[num/2] * 1000) : ((srecords[num/2]+(srecords[num/2-1])/2) * 1000))
puts "min: %1.2fms" % (srecords.first * 1000)
puts "max: %1.2fms" % (srecords.last * 1000)
puts "stddev: %1.2fms" % (Math.sqrt(var) * 1000)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment