tags:

views:

381

answers:

3

Hello, 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
A: 

Use Time.now.to_f

sutch
+3  A: 

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.

sepp2k
+5  A: 

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

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

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

ezpz
in MRI 1.8.7, delta is a float.
Wayne Conrad
It's a float in every version of ruby. Time represents points in time, not spans of time. So the difference between two times could not be a time (the difference between 5 o'clock and 3 o'clock isn't 2 o'clock).
sepp2k
I've changed that to correct the error.
ezpz