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);
|
const Duration _windowsMinSleepTime = Duration(milliseconds: 16);
|
||||||
|
|
||||||
void preciseSleep(Duration duration) {
|
void preciseSleep(Duration duration) {
|
||||||
if (Platform.isWindows && duration < _windowsMinSleepTime) {
|
final stopwatch = Stopwatch()..start();
|
||||||
// Busy-wait for short durations on Windows
|
|
||||||
final end = DateTime.now().add(duration);
|
if (Platform.isWindows) {
|
||||||
while (DateTime.now().isBefore(end)) {}
|
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 {
|
} else {
|
||||||
// Use normal sleep for longer durations or on Unix
|
|
||||||
sleep(duration);
|
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