From df3367f3343ec5acc579205479642d7275f3e12b Mon Sep 17 00:00:00 2001 From: mrsaturnsan <32889818+mrsaturnsan@users.noreply.github.com> Date: Wed, 13 Nov 2024 10:19:21 -0600 Subject: [PATCH] Make delay_usec more precise Comment fix --- platform/windows/os_windows.cpp | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp index ce4ebb03f2f..27201d5efca 100644 --- a/platform/windows/os_windows.cpp +++ b/platform/windows/os_windows.cpp @@ -769,10 +769,22 @@ double OS_Windows::get_unix_time() const { } void OS_Windows::delay_usec(uint32_t p_usec) const { - if (p_usec < 1000) { - Sleep(1); - } else { - Sleep(p_usec / 1000); + constexpr uint32_t tolerance = 1000 + 20; + + uint64_t t0 = get_ticks_usec(); + uint64_t target_time = t0 + p_usec; + + // Calculate sleep duration with a tolerance for fine-tuning. + if (p_usec > tolerance) { + uint32_t coarse_sleep_usec = p_usec - tolerance; + if (coarse_sleep_usec >= 1000) { + Sleep(coarse_sleep_usec / 1000); + } + } + + // Spin-wait until we reach the precise target time. + while (get_ticks_usec() < target_time) { + YieldProcessor(); } }