- 
      
- 
        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
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # 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