How to time an operation in milliseconds in Ruby?

Viewed 65831

I'm wishing to figure out how many milliseconds a particular function uses. So I looked high and low, but could not find a way to get the time in Ruby with millisecond precision.

How do you do this? In most programming languages its just something like

start = now.milliseconds
myfunction()
end = now.milliseconds
time = end - start
10 Answers

You can use ruby's Time class. For example:

t1 = Time.now
# processing...
t2 = Time.now
delta = t2 - t1 # in seconds

Now, delta is a float object and you can get as fine grain a result as the class will provide.

You should take a look at the benchmark module to perform benchmarks. However, as a quick and dirty timing method you can use something like this:

def time
  now = Time.now.to_f
  yield
  endd = Time.now.to_f
  endd - now
end

Note the use of Time.now.to_f, which unlike to_i, won't truncate to seconds.

Also we can create simple function to log any block of code:

def log_time
  start_at = Time.now

  yield if block_given?

  execution_time = (Time.now - start_at).round(2)
  puts "Execution time: #{execution_time}s"
end

log_time { sleep(2.545) } # Execution time: 2.55s
Related