→ Time in irb

14 December 2007

Just like Unix’s time command, in irb. Stick it in yer .irbrc.

def time(times = 1)
  require 'benchmark'
  ret = nil
  Benchmark.bm { |x| x.report { times.times { ret = yield } } }
  ret
end

Now you can do handy things such as:

>> time { sleep 1 }
      user     system      total        real
  0.000000   0.000000   0.000000 (  1.000115)
=> 1

Pass in a number to specify iteration count:

>> time(2) { sleep 1 }
      user     system      total        real
  0.000000   0.000000   0.000000 (  2.000152)
=> 1