Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an idiomatic way to measure time in Ruby?

Tags:

ruby

ruby-2.3

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?

like image 998
B Seven Avatar asked Feb 06 '23 02:02

B Seven


1 Answers

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

require 'benchmark'

result = nil
elapsed = Benchmark.realtime do 
  result = do_something
end
like image 107
Sergio Tulentsev Avatar answered Feb 20 '23 14:02

Sergio Tulentsev