Skip to content

Commit 449d90b

Browse files
committed
Merge pull request #99178 from mrsaturnsan/windows_sleep_precision
Make `delay_usec` more precise on Windows to fix framepacing
2 parents 8d530bc + df3367f commit 449d90b

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
@@ -817,10 +817,22 @@ double OS_Windows::get_unix_time() const {
817817
}
818818

819819
void OS_Windows::delay_usec(uint32_t p_usec) const {
820-
if (p_usec < 1000) {
821-
Sleep(1);
822-
} else {
823-
Sleep(p_usec / 1000);
820+
constexpr uint32_t tolerance = 1000 + 20;
821+
822+
uint64_t t0 = get_ticks_usec();
823+
uint64_t target_time = t0 + p_usec;
824+
825+
// Calculate sleep duration with a tolerance for fine-tuning.
826+
if (p_usec > tolerance) {
827+
uint32_t coarse_sleep_usec = p_usec - tolerance;
828+
if (coarse_sleep_usec >= 1000) {
829+
Sleep(coarse_sleep_usec / 1000);
830+
}
831+
}
832+
833+
// Spin-wait until we reach the precise target time.
834+
while (get_ticks_usec() < target_time) {
835+
YieldProcessor();
824836
}
825837
}
826838

0 commit comments

Comments
 (0)