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.
Code
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: TrueInside 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
Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.