Measure elapsed durations with a clock that cannot go backwards.
How It Works
time.monotonic() returns an arbitrary-origin steadily increasing clock suitable for elapsed-time calculations. Do not convert its value to a calendar date; only differences between observations are meaningful.
Step-by-Step Example
import time
start_counter = time.monotonic()
end_counter = time.monotonic()
print(end_counter - start_counter >= 0)
Understanding the Example
- The expression 'time.monotonic()' supplies the value stored as 'start_counter'. This value is then used or checked by the later statements.
- The expression 'time.monotonic()' supplies the value stored as 'end_counter'. This value is then used or checked by the later statements.
Run the complete example as written, then inspect the displayed result. The values returned by the operation are more important than simply seeing the script finish.
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
Use monotonic_ns() to avoid floating-point rounding for long-running measurements.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Treating monotonic() output as a Unix timestamp or persisting it for comparison across restarts.
- Build a timeout check based on a monotonic deadline.
Key Takeaways
- Measure elapsed durations with a clock that cannot go backwards.
- time.monotonic() returns an arbitrary-origin steadily increasing clock suitable for elapsed-time calculations.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.