Back
+15 XP
Concept

High-Precision Monotonic Timers

Never use `time.time()` for elapsed durations because NTP time syncs can move system clocks backwards. `time.monotonic()` strictly moves forward ⏱️.

python
import time

start = time.monotonic()
total = sum(i for i in range(10000))
elapsed = time.monotonic() - start

print(f"Elapsed: {elapsed:.6f} seconds ⏱️")

# 110. High-Precision Monotonic Timers Never use `time.time()` for elapsed durations because NTP time syncs can move system clocks backwards. `time.monotonic()` strictly moves forward ⏱️. ```python import time start = time.monotonic() total = sum(i for i in range(10000)) elapsed = time.monotonic() - start print(f"Elapsed: {elapsed:.6f} seconds ⏱️") ``` Need even higher precision? `time.monotonic_ns()` returns integer nanoseconds without floating-point rounding errors! ⏱️ --- ### Question Why is `time.monotonic()` preferred over `time.time()` for measuring execution duration? 🧠 - [ ] a. It cannot go backwards when system clocks adjust via NTP synchronization ⏱️ - [ ] b. It converts seconds into milliseconds automatically - [ ] c. It pauses during CPU idle sleep states - [ ] d. It measures time using GPU clock crystals --- ### Challenge Import `time`. Record `t1 = time.monotonic()`, compute `1 + 1`, record `t2 = time.monotonic()`. Print whether `t2 >= t1`. 🎯 <details> <summary>Solution</summary> ```python import time t1 = time.monotonic() _ = 1 + 1 t2 = time.monotonic() print(t2 >= t1) ``` </details>

Checkpoint

Why is `time.monotonic()` preferred over `time.time()` for measuring execution duration? 🧠

Practice

Import `time`. Record `t1 = time.monotonic()`, compute `1 + 1`, record `t2 = time.monotonic()`. Print whether `t2 >= t1`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks