Refactor preciseSleep for improved timing accuracy and reduce busy-wait duration on Windows

This commit is contained in:
ImBenji
2025-11-23 18:08:45 +00:00
parent 8125f8ebd7
commit f5a23fa5c4
2 changed files with 5 additions and 7 deletions

View File

@@ -39,7 +39,7 @@ void spawnTicket(RandomAccessFile file, {
int count = expSleepTracker[label] ?? 0; int count = expSleepTracker[label] ?? 0;
int sleepTime = (1 << count); // Exponential backoff int sleepTime = (1 << count); // Exponential backoff
// sleepTime = max(1, min(sleepTime, 1000)); // Clamp between 1ms and 1000ms // sleepTime = max(1, min(sleepTime, 1000)); // Clamp between 1ms and 1000ms
preciseSleep(Duration(microseconds: sleepTime * 5000)); preciseSleep(Duration(microseconds: sleepTime * 1000));
expSleepTracker[label] = count + 1; expSleepTracker[label] = count + 1;
} }

View File

@@ -234,20 +234,18 @@ void preciseSleep(Duration duration) {
if (Platform.isWindows) { if (Platform.isWindows) {
if (duration < _windowsMinSleepTime) { if (duration < _windowsMinSleepTime) {
// Pure busy-wait for very short durations // Pure busy-wait with high-res timer
final end = DateTime.now().add(duration); while (stopwatch.elapsed < duration) {}
while (DateTime.now().isBefore(end)) {}
} else { } else {
// Hybrid: sleep most of it, busy-wait the remainder // Hybrid: sleep most of it, busy-wait the remainder
final sleepDuration = duration - _windowsMinSleepTime; final sleepDuration = duration - _windowsMinSleepTime;
sleep(sleepDuration); sleep(sleepDuration);
final end = DateTime.now().add(_windowsMinSleepTime); while (stopwatch.elapsed < duration) {}
while (DateTime.now().isBefore(end)) {}
} }
} else { } else {
sleep(duration); sleep(duration);
} }
stopwatch.stop(); stopwatch.stop();
print('preciseSleep: requested ${duration.inMicroseconds}μs, actual ${stopwatch.elapsedMicroseconds}μs, diff ${stopwatch.elapsedMicroseconds - duration.inMicroseconds}μs'); // print('preciseSleep: requested ${duration.inMicroseconds}μs, actual ${stopwatch.elapsedMicroseconds}μs, diff ${stopwatch.elapsedMicroseconds - duration.inMicroseconds}μs');
} }