Skip to content

prefer-monotonic-for-elapsed-time

Use a monotonic clock for a local wall-clock value used only to measure elapsed time.

Why

System-clock corrections can make wall-clock differences negative or unexpectedly large. A monotonic clock measures elapsed intervals without these jumps.

Fix

Use time.monotonic() or time.perf_counter() for both the start reading and its elapsed-time readings. Keep time.time() when measuring absolute timestamps or deliberate wall-clock adjustments.

Examples

Before — flagged A local wall clock measures duration
app/metrics.py
import time
def measure():
started = time.time()
while time.time() - started < 5:
work()
After — preferred A monotonic clock measures duration
app/metrics.py
import time
def measure():
started = time.monotonic()
while time.monotonic() - started < 5:
work()