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
You can use ruby's
Time
class. For example:Now,
delta
is afloat
object and you can get as fine grain a result as the class will provide.Also we can create simple function to log any block of code:
You can also use the built-in Benchmark.measure function:
Prints:
If you use
You're obtaining time in seconds, that is far from accurate, specially if you are timing little chunks of code.
The
absolute_time
gem is a drop-in replacement for Benchmark, but uses native instructions to be far more accurate.Use Time.now.to_f