Today I Learned Monotonic Time
Landon Schropp •
When benchmarking, it's important to differentiate between the wall clock—the current time if you were to look at a clock—and the monotonic clock—a consistently advancing time. (The first is referred to as clock time and the second as monotonic time.)
While the wall clock might seem consistent, it can change for a variety of reasons:
- An update from the Network Time Protocol (NTP) server synchronizes the system time
- Another routine executes
clock_settime - A leap second is added or removed due to the natural variation of the planet circling the sun
The following isn't the most accurate way to measure something because it relies on clock time.
start_time = Time.now
do_something(...)
end_time = Time.now
duration = end_time - start_time
Instead, you can access the monotonic time directly for your benchmark.
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
do_something(...)
end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
duration = end_time - start_time
For more information, check out this great article: The Monotonic Clock and Why You Should Care About It.