Unique Marketing, Guaranteed Results.

How to do Benchmarking with Ruby

May 21st, 2009 by Alan Carl Mitchell

Benchmarking with Ruby is super easy. There is already a built in class–Benchmark–that will do all of the heavy lifting for you.

If you want to do basic benchmarking, Benchmark.bm is the easiest way to go. Take a look below. Here we are going to test three ways to do looping in Ruby and see which one we like best.

require 'benchmark'
 
n = 5000000
 
Benchmark.bm do |x|
  x.report("for loop:")   { for i in 1..n; a = "1"; end }
  x.report("times:")      { n.times do   ; a = "1"; end }
  x.report("upto:")       { 1.upto(n) do ; a = "1"; end }
end

This will produce output something like this:

               user     system      total        real
for loop:  0.727000   0.000000   0.727000 (  0.727030)
times:     0.571000   0.000000   0.571000 (  0.571588)
upto:      0.523000   0.000000   0.523000 (  0.522947)

If we use Benchmark.bmbm, then it will do a ‘rehearsal’ run first in order to better equalize the garbage collection environment of the code inside the block so that hopefully we get more realistic timings.

require 'benchmark'
 
n = 5000000
 
Benchmark.bmbm do |x|
  x.report("for loop:")   { for i in 1..n; a = "1"; end }
  x.report("times:")      { n.times do   ; a = "1"; end }
  x.report("upto:")       { 1.upto(n) do ; a = "1"; end }
end

This will produce output something like this:

Rehearsal ---------------------------------------------
for loop:   0.756000   0.000000   0.756000 (  0.756298)
times:      0.477000   0.000000   0.477000 (  0.476855)
upto:       0.527000   0.000000   0.527000 (  0.526522)
------------------------------------ total: 1.760000sec

                user     system      total        real
for loop:   0.751000   0.000000   0.751000 (  0.751067)
times:      0.516000   0.000000   0.516000 (  0.515874)
upto:       0.581000   0.000000   0.581000 (  0.581254)

Alternately, you can use the Benchmark.realtime method like this:

puts "for loop: #{Benchmark.realtime {for i in 1..n ; a = "1" ; end}}"

and get something like this:

for loop: 0.682438850402832
Copyright © 2005-2011 PMA Media Group. All Rights Reserved