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 sleepTime = (1 << count); // Exponential backoff
// 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;
}

View File

@@ -234,20 +234,18 @@ void preciseSleep(Duration duration) {
if (Platform.isWindows) {
if (duration < _windowsMinSleepTime) {
// Pure busy-wait for very short durations
final end = DateTime.now().add(duration);
while (DateTime.now().isBefore(end)) {}
// Pure busy-wait with high-res timer
while (stopwatch.elapsed < duration) {}
} else {
// Hybrid: sleep most of it, busy-wait the remainder
final sleepDuration = duration - _windowsMinSleepTime;
sleep(sleepDuration);
final end = DateTime.now().add(_windowsMinSleepTime);
while (DateTime.now().isBefore(end)) {}
while (stopwatch.elapsed < duration) {}
}
} else {
sleep(duration);
}
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');
}