When measuring time intervals in a Python program, it is recommended to avoid using time.time()
and choose time.monotonic()
or time.monotonic_ns()
instead.
Problems with time.time()
- Returns the current time in seconds since the epoch (usually January 1, 1970, 00:00:00 UTC).
- Commonly used to measure the time elapsed between two points in a program.
- Not immune to system clock adjustments, like Daylight Saving Time changes or manual clock updates.
Benefits of time.monotonic()
and time.monotonic_ns()
time.monotonic()
- Returns a monotonic clock value, which is a clock that always increases.
- Not affected by system clock adjustments.
- Useful for measuring the time elapsed between two points in a program when you need a clock that won’t be influenced by external factors.
- The returned value is not an absolute timestamp, and its meaning is specific to the program it’s used in.
time.monotonic_ns()
- Similar to
time.monotonic()
, but it returns the value in nanoseconds. - Provides higher resolution for time measurements.
- Useful for measuring small time intervals with high accuracy.
When working with very small time intervals or requiring high-precision measurements, consider using time.monotonic_ns()
instead of time.monotonic()
to avoid the precision loss caused by the float type
Example: Reformatting time.monotonic_ns()
output for human readability
You can easily convert the output of time.monotonic_ns()
to seconds for better readability:
import time
start_ns = time.monotonic_ns()
# Your code here
end_ns = time.monotonic_ns()
elapsed_seconds = (end_ns - start_ns) / 1e9
print(f"Elapsed time: {elapsed_seconds:.5f} seconds")
By using time.monotonic()
or time.monotonic_ns()
instead of time.time()
, you can avoid potential inaccuracies due to system clock adjustments and achieve more reliable time measurements.