Skip to content

Commit df3367f

Browse files
committed
Make delay_usec more precise
Comment fix
1 parent ef8d981 commit df3367f

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

platform/windows/os_windows.cpp

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -769,10 +769,22 @@ double OS_Windows::get_unix_time() const {
769769
}
770770

771771
void OS_Windows::delay_usec(uint32_t p_usec) const {
772-
if (p_usec < 1000) {
773-
Sleep(1);
774-
} else {
775-
Sleep(p_usec / 1000);
772+
constexpr uint32_t tolerance = 1000 + 20;
773+
774+
uint64_t t0 = get_ticks_usec();
775+
uint64_t target_time = t0 + p_usec;
776+
777+
// Calculate sleep duration with a tolerance for fine-tuning.
778+
if (p_usec > tolerance) {
779+
uint32_t coarse_sleep_usec = p_usec - tolerance;
780+
if (coarse_sleep_usec >= 1000) {
781+
Sleep(coarse_sleep_usec / 1000);
782+
}
783+
}
784+
785+
// Spin-wait until we reach the precise target time.
786+
while (get_ticks_usec() < target_time) {
787+
YieldProcessor();
776788
}
777789
}
778790

0 commit comments

Comments
 (0)