Why Does Windows Sleep Lag by 15 ms? Uncovering Scheduler Granularity
A backend process that reports CPU and memory every 10 seconds missed occasional reports on Windows because the Sleep function oversleeps by up to one scheduler time slice, a problem solved by adjusting timing or using higher‑precision wait mechanisms such as Event.wait on Linux.
Background
A simple requirement was to run a background process on a server that reports CPU and memory every 10 seconds. After a few days of data collection, a missing data point was observed on a Windows server between 14:59 and 15:12 on May 24, with the missing entry filled with null. The client logs showed that the process had reported successfully at the expected intervals, prompting further investigation.
The data points showed that the missing entries occurred roughly every 55 minutes, corresponding to a gap of about 320–330 report indices.
Root Cause Investigation
Two hypotheses were examined.
2.1 Hypothesis 1: updateData() takes time
Profiling showed that updateData() execution time was essentially zero, so it could not explain the missing reports.
2.2 Hypothesis 2: Sleep() inaccuracy
Logs revealed that the actual sleep duration was about 15 ms longer than requested. Over a 55‑minute interval this accumulates to roughly one missed report.
Windows uses a 64 Hz scheduler, giving a time slice of 15.625 ms. Because Windows is not a real‑time OS, the Sleep function can round the requested interval to the nearest one or two time slices, resulting in a 0–15.625 ms error.
MSDN documentation confirms that Sleep may wait for one or two scheduler ticks, causing the observed deviation.
Solution
3.1 Official Recommendation
Microsoft suggests adjusting the system timer granularity:
Call timeGetDevCaps to query the minimum timer resolution.
Call timeBeginPeriod before the timing loop to set the timer to the smallest granularity.
Call timeEndPeriod after the loop to restore the original granularity.
Note that changing the timer granularity can affect power consumption and overall scheduling, so it should be used sparingly.
3.2 Developer‑Implemented Fix
Instead of altering the system timer, the code compensates for the oversleep by subtracting the previously accumulated extra time from the next interval, ensuring each cycle stays close to the intended 10 seconds.
dwStart = GetTickCount();
Sleep(dwInterval);
dwDiff = GetTickCount() - dwStart - dwInterval;
dwInterval = m_iInterval*1000;
if (((long)dwDiff > 0) && (dwDiff < dwInterval)) {
dwInterval -= dwDiff;
}How Linux Handles sleep()
On Linux the same reporting task uses the open‑source scheduler APScheduler, which relies on a separate thread and Python’s Event.wait() for timing.
The scheduler’s main loop creates an Event object:
def __init__(self, gconfig={}, **options):
self._wakeup = Event() Event.wait()blocks the thread until the internal flag is set or a timeout occurs, effectively acting as a high‑precision timer.
Measurements showed Event.wait() has an average deviation of 0.1 ms, compared with ~7.6 ms for time.sleep(), confirming its superior accuracy.
APScheduler runs the task in a dedicated thread, so the scheduling loop is not blocked by the task’s execution time, avoiding the timing drift observed on Windows.
Conclusion
Both Windows and Linux sleep() can deviate from the requested interval by up to one scheduler time slice.
Using Event.wait() as a timer yields much higher precision (≈0.1 ms).
APScheduler is an effective Python task‑scheduling library for reliable periodic execution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
