← Back to Home

Eight Ways Python Clocks Disagree on One Millisecond

Pythonclocksperformance

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.

// FLOW_01Order of checks when a duration looks wrong5 NODES01STEP_01get_clock_info to read implementation and adjustable02STEP_02measure the smallest positive delta in a busy loop03STEP_03re-measure with perf_counter_ns04STEP_04decide whether the block is sleep or Event.wait05STEP_05loop on a deadline instead of a single sleepEND_OF_FLOW
Order of checks when a duration looks wrong · diagram drawn from this article
Python
Technologies referenced · icons from Simple Icons (CC0)

The eight behaviours in one table

SymptomThe usual assumptionMeasured here (Win11 26300 / CPython 3.13.14)
Granularity of process_timethe 100 ns its resolution field reportsquantum 15.625 ms; a 1 ms busy loop reads 0.0
process_time on a waitrepresents the cost of a request1 s of sleep adds 0.000000
Waiting 1 msit takes 1 mstime.sleep 1.56 ms, Event.wait 15.62 ms
Stability of that waiterror within microsecondsEvent.wait(0.001) from 1.14 ms to 17.63 ms
Accuracy of a sleep looperror does not accumulate200 iterations of 1 ms overshoot by 40.2%
Precision of time.time()microsecond levelfloat step 238 ns, 14% of calls repeat the previous value
perf_counter vs monotonictwo independent clocksthe same QueryPerformanceCounter()
Whether time.time() can go backalways increasingadjustable=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:

CallFastestMedianSlowest
time.sleep(0.001)1.076 ms1.564 ms2.329 ms
kernel32.Sleep(1) via ctypes1.375 ms15.326 ms16.881 ms
threading.Event().wait(0.001)1.140 ms15.620 ms17.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:

CallDefaultAfter timeBeginPeriod(1)After timeEndPeriod(1)
time.sleep(0.001)1.564 ms1.566 msnot measured
kernel32.Sleep(1)15.326 ms1.989 msnot measured
Event.wait(0.001)15.620 ms1.107 ms14.662 ms
Event.wait(0.010)16.742 ms10.383 msnot 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

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.

☁️ DigitalOcean Cloud ⚡ Vultr VPS 🤖 QoderWork CN (Refer & Earn) ☁️ Aliyun AI Products 📚 WordPress Books 🧠 AI & LLM Books 🏗️ System Design Books 🐳 Docker & K8s Books 🐧 Linux Admin Books 🐍 Python Books 🗄️ Database Books 🚀 DevOps & SRE Books 🤖 Xiaomi MiMo Platform
← Back to Home