Wall Clocks vs. Monotonic Clocks
When you write code that deals with time, you might think getting the current time is simple. But beneath the surface, there are two different kinds of “clocks” your system uses, and choosing the wrong one can lead to mysterious bugs and incorrect measurements. Let’s break down the difference between a Wall Clock and a Monotonic Clock.
Imagine you need to time a 100-meter sprint. You have two options:
Which one would you trust for an accurate result? Almost certainly the stopwatch. This simple analogy is the key to understanding the two clocks in your computer.
A Wall Clock (or system_clock) tells you the current, human-readable date and time. It’s what you’d use to answer the question, “What time is it right now?” Its goal is to be accurate according to the real world.
Wall Clocks are not reliable for measuring time intervals. Because they can suddenly jump forward or even go backward. This can happen for several reasons:
Measuring a negative duration is impossible, but with a Wall Clock, your code might report it. This is why you should never use a Wall Clock for performance benchmarks or calculating timeouts.
A Monotonic Clock (steady_clock or perf_counter) is designed for one purpose: to measure elapsed time intervals accurately. Its defining feature is that it only ever moves forward.
Think of it as a stopwatch that starts counting from zero when your system boots up. The absolute value it gives you is meaningless (it’s just a large number of nanoseconds since booting the system), but the difference between two readings is incredibly precise and reliable. It isn’t affected by NTP syncs, Daylight Saving Time, or any other adjustments to the system’s Wall Clock.