Measuring elapsed time with Ruby
Over the weekend I was working on a side project and I found myself needing to improve the speed of certain methods, so looked up some ways to measure time in Ruby for this purpose.
Several posts gave the obvious answer - set a start_time variable at start, set an end_time variable at end and calculate the difference. Easy. But not necessarily the best answer.
The problem with that approach, which Luca Guidi in this blog post nicely spells out, is that Time.now gets the current time from the system, but the system is not meant for measuring duration.
The reason for this is that wall-clock time can be adjusted forward or backward by clock synchronization, manual changes, or the operating environment. That means that system time should not be relied on for measuring elapsed time, especially when measuring short durations such as milliseconds.
The Better Way
There is another approach that avoids the issues mentioned above. It uses the Monotonic Clock.
The Monotonic Clock behaves similarly to how a stopwatch or timer would behave. It increases from an unspecified starting point and is intended for measuring intervals. Its absolute value has no calendar meaning.
That means that we can measure elapsed time in Ruby without being affected by wall-clock adjustments:
starting = Process.clock_gettime(Process::CLOCK_MONOTONIC)
# Process that you're measuring
ending = Process.clock_gettime(Process::CLOCK_MONOTONIC)
elapsed = ending - starting
elapsed # => 5.702740999986418 (seconds)