Ruby Tuesday – Benchmark::realtime

Today’s Ruby Tuesday is on Benchmark::realtime.

How many times have you written this Ruby method?

def time_it
  start = Time.now  
  yield
  Time.now - start
end

And truthfully, how many different times have you seen this method defined in the same application even?

We all know this method, and have likely written it, even if it was in other programming languages. It is the standard, “How long is this part of the code taking?” wrapper that we decide we should generalize into a method.

time_it { (1..20000).map{|x| x * x * x} }
# => 0.004334
time_it { (1..200000).map{|x| x * x * x} }
# => 0.029896
time_it { (1..2000000).map{|x| x * x * x} }
# => 0.414218
time_it { (1..20000000).map{|x| x * x * x} }
# => 8.827975

There is good news about this though. The Ruby language team has written this for you and all you have to do is require 'benchmark' to get access to it. It is Benchmark::realtime.

require 'benchmark'
# => true
Benchmark.realtime { (1..20000000).map{|x| x * x * x} }
# => 6.681451

And make sure to check out the Benchmark module for other methods such as measure, which gives you a breakdown of the user CPU time, the system CPU time, total CPU time, total elapsed time and time of children processes.

Benchmark.measure { (1..20000000).map{|x| x * x * x} }
# => #<Benchmark::Tms:0x007f89ce401cf8
#  @cstime=0.0,
#  @cutime=0.0,
#  @label="",
#  @real=13.406651,
#  @stime=3.1399999999999997,
#  @total=12.549999999999997,
#  @utime=9.409999999999997>

–Proctor