B Seven B Seven - 2 months ago 7
Ruby Question

What is an idiomatic way to measure time in Ruby?

This is pretty ugly:

t = Time.now
result = do_something
elapsed = Time.now - t


I tried this:

elapsed = time do
result = do_something
end

def time
t = Time.now
yield
Time.now - t
end


This is better. But the problem is that
result
falls out of scope after the block ends.

So, is there a better way of doing timing? Or a good way to use the
result
?

Answer

A really idiomatic way would be to use the standard library. :)

require 'benchmark'

result = nil
elapsed = Benchmark.realtime do 
  result = do_something
end
Comments