Improve preciseSleep function for Windows with hybrid sleep strategy and logging
This commit is contained in:
@@ -230,12 +230,24 @@ extension SweepstoreDateTimeHelper on DateTime {
|
||||
const Duration _windowsMinSleepTime = Duration(milliseconds: 16);
|
||||
|
||||
void preciseSleep(Duration duration) {
|
||||
if (Platform.isWindows && duration < _windowsMinSleepTime) {
|
||||
// Busy-wait for short durations on Windows
|
||||
final end = DateTime.now().add(duration);
|
||||
while (DateTime.now().isBefore(end)) {}
|
||||
final stopwatch = Stopwatch()..start();
|
||||
|
||||
if (Platform.isWindows) {
|
||||
if (duration < _windowsMinSleepTime) {
|
||||
// Pure busy-wait for very short durations
|
||||
final end = DateTime.now().add(duration);
|
||||
while (DateTime.now().isBefore(end)) {}
|
||||
} 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)) {}
|
||||
}
|
||||
} else {
|
||||
// Use normal sleep for longer durations or on Unix
|
||||
sleep(duration);
|
||||
}
|
||||
|
||||
stopwatch.stop();
|
||||
print('preciseSleep: requested ${duration.inMicroseconds}μs, actual ${stopwatch.elapsedMicroseconds}μs, diff ${stopwatch.elapsedMicroseconds - duration.inMicroseconds}μs');
|
||||
}
|
||||
Reference in New Issue
Block a user