Measure Elapsed Time with Monotonic Clocks
Core idea
Wall-clock time represents civil or epoch time and can be adjusted. time.monotonic measures a clock that does not go backward; compare readings from the same clock, not their absolute values. monotonic_ns returns integer nanoseconds. perf_counter is intended for measuring short durations.
import timestart = time.monotonic_ns()value = sum(range(100))elapsed = time.monotonic_ns() - startprint(value, elapsed >= 0)The calculation is fixed; elapsed time is variable, so test only nonnegativity.
Apply a deadline to fixed sample readings
start = 1000budget = 500deadline = start + budgetfor now in (1499, 1500, 1501): print(now >= deadline)These synthetic readings represent values from one monotonic clock. The exact boundary is treated as expired.
Common mistake
Do not mix time.time readings with monotonic readings or serialize monotonic timestamps as calendar dates. Do not assert exact elapsed time in a test.
Practice
Measure a bounded computation with perf_counter_ns; report the duration but check only that it is nonnegative. Then test a timeout predicate on fixed inputs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Elapsed clocks
Check your understanding of monotonic clocks.
What is printed?
import timea=time.monotonic_ns()b=time.monotonic_ns()print(b>=a)What is printed?
import timeprint(isinstance(time.monotonic_ns(),int))Which clock is suitable for a timeout deadline?
How should a measured duration be tested?