Monotonic Time Backport

1.6 · maintenance · verified Sun Apr 05

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

Install

Imports

Quickstart

This quickstart demonstrates how to use the `monotonic` function to measure elapsed time, ensuring that clock adjustments do not affect the duration measurement. It includes a robust import pattern for compatibility across Python 2 and Python 3.3+.

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')

view raw JSON →