Understand why the system clock is not a reliable stopwatch.
How It Works
Wall-clock time represents a date and time and can jump when the system adjusts its clock. monotonic() advances steadily and is designed for measuring intervals. Use datetime.now() to display calendar times and monotonic() or perf_counter() to measure elapsed work.
Monotonic and performance counters should be compared by subtracting two readings from the same clock.
Step-by-Step Example
from datetime import datetime, timezone
from time import monotonic, sleep
started_at = datetime.now(timezone.utc)
start_counter = monotonic()
sleep(0.01)
elapsed = monotonic() - start_counter
print(started_at.tzinfo is not None)
print(elapsed >= 0)
Understanding the Example
- The expression 'datetime.now(timezone.utc)' supplies the value stored as 'started_at'. This value is then used or checked by the later statements.
- The expression 'monotonic()' supplies the value stored as 'start_counter'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
True
True
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
Time a small function with perf_counter() and show the wall-clock timestamp separately.
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
- Subtracting readings of time.time() and assuming the result cannot be affected by clock changes.
- Interpreting a monotonic counter reading as a calendar timestamp.
Key Takeaways
- Understand why the system clock is not a reliable stopwatch.
- Wall-clock time represents a date and time and can jump when the system adjusts its clock.
- Monotonic and performance counters should be compared by subtracting two readings from the same clock.