Monotonic Time Backport
This library provides a backport of Python's `time.monotonic()` function for older Python environments (Python 2 and Python < 3.3). It offers a monotonic clock, guaranteed not to go backward, which is crucial for reliably measuring elapsed time, as it remains unaffected by system clock adjustments such as daylight saving changes. The current version is 1.6. The library is considered stable and complete, with no further updates planned, as `time.monotonic()` is integrated into the standard library for Python 3.3 and newer.
Warnings
- deprecated For Python 3.3 and newer, `time.monotonic()` is part of the standard library. Using this `monotonic` package on these versions is redundant and unnecessary, though it will gracefully alias the built-in function. Prefer `time.monotonic()` directly for modern Python versions to avoid unnecessary dependencies.
- gotcha The value returned by `monotonic.monotonic()` (or `time.monotonic()`) has an undefined reference point. Only the *difference* between two calls to the function is meaningful for measuring elapsed time; the absolute value itself should not be relied upon. Comparing values from different processes might also be unreliable on some OS.
- gotcha The precision of the monotonic clock can vary by operating system. Specifically, on some Windows implementations, `monotonic.monotonic()` (and `time.monotonic()`) might offer less decimal precision compared to `time.time()`, typically around three decimal places.
- breaking If the `monotonic` library cannot find a suitable underlying system implementation for a monotonic clock on the current platform, attempting to import the module or its functions will raise a `RuntimeError`.
Install
-
pip install monotonic
Imports
- monotonic
import monotonic start = monotonic.monotonic()
Quickstart
import time
# For compatibility across Python versions, prefer this pattern:
try:
from time import monotonic as get_monotonic_time_fn
except ImportError:
# Fallback for Python 2 and Python < 3.3 using the 'monotonic' package
from monotonic import monotonic as get_monotonic_time_fn
print('Starting a monotonic timer...')
start_time = get_monotonic_time_fn()
# Simulate some work
time.sleep(2.5)
end_time = get_monotonic_time_fn()
elapsed_time = end_time - start_time
print(f'Elapsed time: {elapsed_time:.3f} seconds')