Ruby – How to time an operation in milliseconds in Ruby

rubytimer

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

Best Answer

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.