perf_counter Measures Elapsed Without Wall Jumps

monotonic and perf_counter clocks only move forward, making them the tools for durations; time.time() stays reserved for wall-clock timestamps.

PythonCli Tooling

Code

pythonsnippet
20 lines
import time

# time.time() is a wall clock: NTP steps or manual changes can move it backwards,
# so differences measured across it are not reliable durations
# perf_counter() and monotonic() never go backwards — they are for durations
start = time.monotonic()
work = sum(i * i for i in range(100_000))
elapsed = time.monotonic() - start
print("monotonic elapsed >= 0:", elapsed >= 0)

# perf_counter() offers the highest resolution available on the platform
start = time.perf_counter()
time.sleep(0.01)
measured = time.perf_counter() - start
print("perf_counter saw the ~10ms sleep:", 0.005 <= measured < 0.2)

# Rules of thumb: monotonic()/perf_counter() for "how long did this take",
# time.time() for "what is the wall-clock timestamp" (schedules, logs, storage)
print("time.time() is a wall timestamp:", time.time() > 1_500_000_000)
print("they are different clocks:", time.monotonic() < time.time())

Output

Captured from a sandboxed run of this snippet in the build pipeline.

monotonic elapsed >= 0: True
perf_counter saw the ~10ms sleep: True
time.time() is a wall timestamp: True
they are different clocks: True

Inside the snippet

Four module-level bindings drive the timing demo: start captures time.monotonic(), work burns the sample workload, and elapsed/measured hold the measured differences.

What to watch for

  • Nothing to install: the snippet stays inside the standard library.

Using it

The file announces its steps in the output: monotonic elapsed >= 0:, perf_counter saw the ~10ms sleep:, time.time() is a wall timestamp:.

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `time`. Its state lives in module-level bindings: `start`, `work`, `elapsed`.