Eight Ways Python Clocks Disagree on One Millisecond
I took the same "wait one millisecond" intent and wrote it five different ways, then ran each twenty to thirty times on a Windows 11 build 26300 machine with CPython 3.13.14 recording the actual elapsed time. The spread is not noise. It is the same intent getting numbers ten times apart: time.sleep(0.001) lands at a 1.56 ms median, threading.Event().wait(0.001) at 15.62 ms, and kernel32.Sleep(1) at 15.33 ms.
This is not an article about which timer function is faster. It answers the question that comes before that one: is the ruler you measure time with accurate, and whose time is it measuring? Every number here is reproducible on your own machine, the code is at the end, and every error message is copied from what this machine actually raised.
TL;DR: measure elapsed time with perf_counter_ns(), measure deadlines with monotonic(), measure CPU only with process_time(), and never swap them. The number reported by get_clock_info().resolution is not the real step size. Short sleeps must be driven by a deadline loop, not by a single sleep call.
get_clock_info("process_time").resolutionreports1e-07, but the measured quantum is0.015625seconds (15.625 ms), five orders of magnitude apart- Using
process_time()to time a 1 ms and a 5 ms busy loop returned 0.0 in all ten samples process_time()grows by0.000000acrosssleep(1.0)whileperf_counter()grows by1.000696- Waiting 1 ms:
time.sleepmedian 1.56 ms,Event.waitmedian 15.62 ms, a 15x spread between fastest and slowest - After
timeBeginPeriod(1)both collapse to 1–2 ms, and aftertimeEndPeriod(1)Event.waitreturns to 14.66 ms, which is the root-cause evidence - One hundred
sleep(0.01)calls take 1.093 s (+9.3%); two hundredsleep(0.001)calls take 0.280 s (+40.2%) - At epoch scale the float step of
time.time()is fixed at 2⁻²² seconds (238 ns), and 200,000 back-to-back calls produced only 171,695 distinct values perf_counter()andmonotonic()are the same clock on 3.13; Windows has notime.CLOCK_*at all, soclock_gettimeraises AttributeError
The eight behaviours in one table
| Symptom | The usual assumption | Measured here (Win11 26300 / CPython 3.13.14) |
|---|---|---|
Granularity of process_time | the 100 ns its resolution field reports | quantum 15.625 ms; a 1 ms busy loop reads 0.0 |
process_time on a wait | represents the cost of a request | 1 s of sleep adds 0.000000 |
| Waiting 1 ms | it takes 1 ms | time.sleep 1.56 ms, Event.wait 15.62 ms |
| Stability of that wait | error within microseconds | Event.wait(0.001) from 1.14 ms to 17.63 ms |
| Accuracy of a sleep loop | error does not accumulate | 200 iterations of 1 ms overshoot by 40.2% |
Precision of time.time() | microsecond level | float step 238 ns, 14% of calls repeat the previous value |
perf_counter vs monotonic | two independent clocks | the same QueryPerformanceCounter() |
Whether time.time() can go back | always increasing | adjustable=True, docs say a smaller value can be returned |
One: the resolution reported by get_clock_info is not the step it actually moves in
Start with what the five clocks say about themselves. No third-party package needed:
import time
for name in ("time", "monotonic", "perf_counter", "process_time", "thread_time"):
ci = time.get_clock_info(name)
print(f"{name:13s} {ci.implementation:32s} mono={ci.monotonic} adj={ci.adjustable} res={ci.resolution}")
Output on this machine:
time GetSystemTimePreciseAsFileTime() mono=False adj=True res=1e-07
monotonic QueryPerformanceCounter() mono=True adj=False res=1e-07
perf_counter QueryPerformanceCounter() mono=True adj=False res=1e-07
process_time GetProcessTimes() mono=True adj=False res=1e-07
thread_time GetThreadTimes() mono=True adj=False res=1e-07
Five clocks, five identical 1e-07 values. That cannot be literally true: GetProcessTimes on Windows is driven by the scheduler tick, and it does not update every 100 nanoseconds. So I wrote a busy loop that only records the delta at the moment the value changes, then prints the distinct deltas:
def quantum(fn, iterations=3_000_000):
prev = fn()
deltas = []
for _ in range(iterations):
cur = fn()
if cur != prev:
deltas.append(cur - prev)
prev = cur
return sorted(set(deltas))
Three million iterations take about 1.2 seconds. process_time changed 77 times, and the only delta in the set is 0.015625. thread_time behaved the same way, 70 changes, again a single distinct delta of 0.015625. That is 1/64 of a second, exactly the 15.625 ms default Windows clock interrupt.
Compare the smallest increment of time.time() under the same treatment: 2.384185791015625e-07, which is 2⁻²² seconds. That number is not the system precision, it is the smallest step a float64 can represent around 1.79e9. Section six deals with that separately.
So the resolution field describes how finely the returned value can be expressed, not how often it changes. For process_time and thread_time those two numbers differ by a factor of 156,250.
One more cut. Timing short busy loops with process_time gives this, where the first number in each pair is process_time and the second is perf_counter:
target=1 ms -> (0.0, 0.001099) (0.0, 0.001173) (0.0, 0.001039) (0.0, 0.001020) (0.0, 0.001020)
target=5 ms -> (0.0, 0.005028) (0.0, 0.005097) (0.0, 0.005089) (0.0, 0.005305) (0.0, 0.005026)
target=10 ms -> (0.0, 0.010195) (0.0, 0.010060) (0.015625, 0.010045) (0.0, 0.010036) (0.015625, 0.010078)
At 1 ms and 5 ms, process_time read 0.0 in every single sample. At 10 ms only two of five crossed a tick. If you instrument a per-request CPU metric and the request takes a few milliseconds, that field will reliably report zero. The log then looks like "this endpoint barely uses CPU", when in reality it never crossed the 15.625 ms step.
Two: process_time cannot see a wait, one second of sleep adds zero
The documentation for process_time() is explicit: it returns the sum of system and user CPU time of the process, and It does not include time elapsed during sleep.
That sentence looks harmless until you use it in the wrong place. Measured:
across sleep(1.0): process_time delta = 0.000000, perf_counter delta = 1.000696
0.73 s busy loop: process_time = 0.734375, perf_counter = 0.731267
0.734375 deserves a second look: it equals 47 times 0.015625, exactly 47 ticks. The loop really took 0.731 s, process_time reported 0.734 s, a 3 ms error. At second granularity that is irrelevant; at millisecond granularity it is the entire error budget.
So there is exactly one question to answer first: are you measuring how much CPU this code consumed, or how long the user waited? A database query, a network call, a lock, a disk read are all the second kind. Timing them with process_time yields a beautiful, completely wrong, very small number. The reverse also holds: to decide whether a process is spinning, process_time is the right tool because ten minutes of blocked I/O cannot contaminate it.
Three: waiting one millisecond costs 1.5 ms one way and 15.6 ms the other
This is the most valuable result of the round. Three calls, identical intent, wait one millisecond:
| Call | Fastest | Median | Slowest |
|---|---|---|---|
time.sleep(0.001) | 1.076 ms | 1.564 ms | 2.329 ms |
kernel32.Sleep(1) via ctypes | 1.375 ms | 15.326 ms | 16.881 ms |
threading.Event().wait(0.001) | 1.140 ms | 15.620 ms | 17.630 ms |
Raise the request to 10 ms and time.sleep obeys at 10.33 ms, while Sleep(10) takes 16.84 ms and Event.wait(0.010) takes 16.74 ms. Both are still being pushed to the next 15.625 ms boundary.
Note the fastest Event.wait sample, 1.14 ms, against a 15.62 ms median. The same call takes 1 ms when it lands near a tick edge and 17 ms when it lands just after one. That jitter is harder to diagnose than a systematic bias, because in a sample it shows up as "sometimes fast" and gets dismissed as noise.
What does that do to real code? A polling loop that calls event.wait(0.001) as a "1 ms backoff" is really backing off by at least 15 ms. In bulk it is obvious:
500 ms budget: 46 iterations of Event.wait(0.001), 10.886 ms each (nominal 1 ms)
500 ms budget: 319 iterations of time.sleep(0.001), 1.568 ms each
Same wall-clock budget, 46 laps versus 319. If your worker polls with Condition.wait(timeout=0.001) or probes with Queue.get(timeout=0.001), those paths are marching to a 15.6 ms beat, while time.sleep is not.
Four: raise the system timer resolution and both numbers collapse together
Up to here this is correlation. To pin the cause, change one variable: Windows lets a process raise the system timer resolution from the default 15.625 ms to 1 ms with timeBeginPeriod. Same calls, before and after:
| Call | Default | After timeBeginPeriod(1) | After timeEndPeriod(1) |
|---|---|---|---|
time.sleep(0.001) | 1.564 ms | 1.566 ms | not measured |
kernel32.Sleep(1) | 15.326 ms | 1.989 ms | not measured |
Event.wait(0.001) | 15.620 ms | 1.107 ms | 14.662 ms |
Event.wait(0.010) | 16.742 ms | 10.383 ms | not measured |
Three things hold at once. First, Sleep(1) and Event.wait(1 ms) track the resolution exactly. Second, time.sleep does not move at all, because it is not on that path. Third, timeEndPeriod snaps everything back immediately.
The official docs line up. Microsoft's Sleep page says the system clock ticks at a constant rate, that if dwMilliseconds is less than the clock resolution the thread may sleep for less than the requested time, that a value between one and two ticks lands anywhere in that window, and that you should call timeBeginPeriod when you need more accuracy. One detail is worth recording: the doc says "may sleep for less", while I measured longer. The direction differs, but both point at the same fact, which is that the parameter counts ticks, not seconds.
The Python side lines up too. The time.sleep docs note under the 3.11 change that On Windows, a waitable timer is now used, and the Windows implementation section states that on Windows 10 and newer the implementation uses a high-resolution timer with 100 ns resolution. In other words, time.sleep since 3.11 bypasses the system tick, while Event.wait, Condition.wait and Queue.get(timeout=) go through timed lock waits that are still bound by it. Inside one standard library, two waiting paths differ in precision by a factor of ten.
Five: sleeps accumulate, one hundred 10 ms naps cost 1.09 s
A single sleep is "at least" N milliseconds, and that "at least" compounds:
100 x sleep(0.01): nominal 1.000000, actual 1.093047, +9.30%
200 x sleep(0.001): nominal 0.200000, actual 0.280489, +40.24%
The per-call data shows where the money goes: sleep(0.01) has a 10.347 ms median, about 0.35 ms of overhead each time; sleep(0.001) has a 1.564 ms median, about 0.56 ms of overhead. The shorter the sleep, the worse the relative error, because the overhead is fixed while the divisor is tiny.
That matters for rate limiters, heartbeats and pollers. A token refill loop meant to run 100 times per second, written as for _ in range(100): time.sleep(0.01), actually has a 1.09 s period. Run it for an hour and you are more than two minutes behind, and nothing raises an error; downstream just notices you refill slowly.
The fix is to sleep toward a deadline so the error cancels itself:
import time
def sleep_until(deadline):
while True:
left = max(0.0, deadline - time.monotonic())
if left == 0.0:
return
time.sleep(left)
t0 = time.monotonic()
for i in range(100):
sleep_until(t0 + (i + 1) * 0.01)
Each round subtracts whatever the previous round overshot. On this machine, 100 rounds of 10 ms finished in 1.0003 s, taking the error from 9.3% down to 0.03%.
Six: float gives you 238 nanoseconds, and 14% of calls repeat
time.time() returns a float. Epoch seconds are around 1.795e9, which needs 31 bits for the integer part, leaving 21 bits of the 52-bit mantissa for the fraction. The smallest step is therefore 2⁻²² seconds.
Both measurements confirm it:
smallest positive delta in a 0.5 s busy loop: 2.384185791015625e-07 (258 distinct deltas, all multiples of it)
200000 back-to-back time.time() calls: 171,695 distinct values (85.8%)
200000 back-to-back time.time_ns() calls: 200,000 distinct values (100%)
50000 datetime.now() calls: 40,586 distinct values (81.2%)
time_ns() is distinct every time, so the underlying resolution is fine; float is what throws precision away. At millisecond logging nobody cares, but if you use time.time() as a unique key, sort at microsecond level, or compare two timestamps with ==, you will hit the case where two different instants share one float.
time_ns(), monotonic_ns() and perf_counter_ns() return ints and do not have this problem. One adjacent trap: datetime.fromtimestamp(0.9999999) returned 1970-01-01 08:00:01 here, not 08:00:00.999999, because it rounds and jumps across the second boundary.
Seven: perf_counter and monotonic are the same clock on 3.13
Look again at the implementation column from section one: monotonic and perf_counter both report QueryPerformanceCounter(). That is not a coincidence. The perf_counter() docs carry a 3.13 change note reading Use the same clock as time.monotonic().
The two also agree over a 2 second sleep: monotonic advanced 2.000646, perf_counter advanced 2.000665, a 19 microsecond gap that comes from reading them at slightly different moments. Over 3 seconds, time.time() and perf_counter drifted by 3 microseconds.
So why does the documentation keep them as two functions? Because these are platform contracts, not implementation facts. monotonic() promises a clock that cannot be set and is unaffected by system clock updates; perf_counter() promises the highest available resolution and includes time spent sleeping. On some platforms and some CPython versions those promises resolve to different underlying clocks. They happen to be the same clock on Windows in 3.13.
The practical consequence: do not design around the coincidence. Measure duration with perf_counter, compute deadlines with monotonic. Swapping them will not break on this machine, but it can on another interpreter or platform.
There is a harder platform difference too: Windows has no time.CLOCK_* constants at all, and no time.clock_gettime attribute:
hasattr(time, "CLOCK_MONOTONIC") = False
CLOCK_ constants in dir(time) = []
time.clock_gettime -> AttributeError
The docs mark clock_gettime and clock_getres as Availability: Unix. Code copied from Linux that calls time.clock_gettime(time.CLOCK_MONOTONIC) dies on its first line on Windows, and it dies because the attribute does not exist, not because precision differs.
Eight: time.time can be set back, and its Windows source just changed
get_clock_info("time") reports adjustable=True. The documentation defines that field as whether the clock can be set to jump forward or backward, and adds Does not refer to gradual NTP rate adjustments. In other words, adjustable=False would not mean NTP slewing is absent; it only means you cannot move the clock yourself.
The time.time() docs state the risk directly: While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.
Which means any t1 - t0 where both ends come from time.time() can in theory come out negative. I did not actually change the system clock here (it needs administrator rights and would disturb other work on this machine), so treat that point as the documented contract rather than an experiment.
There is one change I can confirm by measurement: the Windows clock source behind time.time() changed in 3.13. The changelog says Changed in version 3.13: On Windows, calls GetSystemTimePreciseAsFileTime() instead of GetSystemTimeAsFileTime(), and this machine's implementation field reads GetSystemTimePreciseAsFileTime().
Why does that matter? Because the widely repeated claim that "time.time() on Windows only has 15.6 ms precision" no longer holds on 3.13. My measured smallest increment is 238 ns, limited by float rather than by the system clock. The old claim was not wrong, it expired. Check the implementation field instead of trusting a remembered number.
Troubleshooting: three real exceptions
All three came up while I was writing the probe scripts. The messages are copied verbatim.
Error one: ValueError: sleep length must be non-negative
Cause: passing "time remaining" straight into sleep(). Once the deadline has passed, deadline - now is negative. This is common in retry backoff, where the first attempt overruns and the second computes a negative remainder.
Fix: clamp to zero first, then decide whether to sleep at all.
left = deadline - time.monotonic()
if left == max(0.0, left) and left:
time.sleep(left)
Error two: TypeError: 'str' object cannot be interpreted as an integer
Cause: the sleep argument came from a config file or environment variable as the string "1" or "0.5". sleep will not coerce it and raises a type error. The same applies to Event.wait("0.001").
Fix: convert once at the boundary with float(...) and validate non-negative, because a negative number then raises the ValueError from error one. Two failure modes hiding in one field.
Error three: AttributeError: module 'time' has no attribute 'clock_gettime'
Cause: inheriting time.clock_gettime(time.CLOCK_MONOTONIC) from Linux code. Windows has neither the function nor the constants.
Fix: keep cross-platform code on the time.monotonic() and monotonic_ns() layer. If you genuinely need platform-specific CLOCK_* logic, branch on hasattr(time, "CLOCK_MONOTONIC") explicitly instead of crashing at runtime.
A set of timing helpers you can copy
Four rules, four functions:
import time
def elapsed_ms(fn):
"""Elapsed time of a call: perf_counter_ns avoids the float loss"""
t0 = time.perf_counter_ns()
result = fn()
return (time.perf_counter_ns() - t0) / 1e6, result
def cpu_ms(fn):
"""CPU time only: sleeps, waits and blocking IO are excluded"""
t0 = time.process_time_ns()
result = fn()
return (time.process_time_ns() - t0) / 1e6, result
def sleep_until(deadline_monotonic):
"""Sleep toward a deadline so the error cannot accumulate"""
while True:
left = max(0.0, deadline_monotonic - time.monotonic())
if left == 0.0:
return
time.sleep(left)
def wait_or_poll(cond, timeout):
"""For millisecond polling, drive the cadence yourself instead of Condition.wait"""
deadline = time.monotonic() + timeout
while not cond():
left = deadline - time.monotonic()
if left == max(0.0, left) and left:
time.sleep(left)
else:
return False
return True
The order of choice: ask what you are measuring. User-visible latency, use perf_counter_ns. CPU consumption, use process_time_ns. Whether something timed out, compute a deadline with monotonic. Anything that has to wait, prefer time.sleep, because on this machine it is ten times more precise than a condition variable.
Where this stops
- Windows 11 build 26300 with CPython 3.13.14 only. Linux and macOS will differ: on Linux
time.sleepusesclock_nanosleep,CLOCK_MONOTONICexists, andtime.time()precision comes fromclock_getres(CLOCK_REALTIME) - The system timer resolution can be raised by any other process (browsers, games and audio tools all call
timeBeginPeriod), soEvent.waitnumbers on the same machine can differ between runs. That is why every group here ran 20 to 30 times and reports medians - The system clock was not actually changed, so the "may return a lower value" point in section eight is the documented contract, not a local experiment
- Only millisecond-scale sleeps and waits were tested. Second-scale, sub-millisecond and cross-process shared-memory waits are not covered
- asyncio's
call_laterand the event loop clock are a separate path and are not covered here
The same "the return value is not the result" family shows up in neighbouring layers. Reading profiler output instead of the clock itself leads to eight profiling misreads; timeouts and cancellation in asyncio have six silent failures; and comparisons of instants, including DST, are covered in six zoneinfo traps. This article only covers the duration side.
This article contains no affiliate links.
FAQ
Q: So which one should I use, time.perf_counter() or time.monotonic()?
perf_counter() for "how long did this take", because its documented promise is the highest available resolution. monotonic() for "when does this time out", because its promise is that it cannot go backwards. On Windows with 3.13 they are the same underlying clock, so swapping them will not fail here, and that is exactly why you should not encode the coincidence into a design.
Q: Given that Event.wait costs 15 ms, should every Queue.get(timeout=0.001) become a sleep poll?
No. A blocking wait with a timeout is not a precision timer; its contract is "return when there is work or the timeout expires", not "sleep exactly N milliseconds". Rewrite only the places where the logic genuinely depends on coming back within a millisecond. Busy polling burns CPU and is not a substitute for blocking.
Q: Why do two runs on the same machine give very different Event.wait numbers?
Because the timer resolution is global and any process calling timeBeginPeriod changes it for everyone. The other half is where your call lands relative to a tick edge, which decides between roughly 1 ms and 17 ms. To reproduce reliably, pin the resolution first (or check it with a tool such as clockres) and take medians over many runs rather than trusting one sample.
Q: If process_time cannot see waits, why keep it at all?
Because it answers a different question cleanly: is this code computing, or is it waiting? How much CPU a process consumed, whether a parsing loop is spinning, whether a batch job is actually blocked on I/O. perf_counter gets polluted by waits in those questions; process_time does not. The prerequisite is knowing it moves in 15.625 ms steps, so never use it on short requests.
👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference
👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation
📌 This article was AI-assisted generated and human-reviewed | TechPassive — An AI-driven content testing site focused on real tool reviews
🔗 Recommended Tools
These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:
As an Amazon Associate, I earn from qualifying purchases at no extra cost to you.