[][src]Crate spin_sleep

Accurate sleeping. Only use native sleep as far as it can be trusted, then spin.

The problem with thread::sleep is it isn't always very accurate, and this accuracy varies on platform and state. Spinning is as accurate as we can get, but consumes the CPU rather ungracefully.

This library adds a middle ground, using a configurable native accuracy setting allowing thread::sleep to wait the bulk of a sleep time, and spin the final section to guarantee accuracy.


Simplest usage with default native accuracy is a drop in replacement for thread::sleep.

spin_sleep::sleep(Duration::new(1, 12_550_000));

More advanced usage, including setting a custom native accuracy, can be achieved by constructing a SpinSleeper.

// Create a new sleeper that trusts native thread::sleep with 100μs accuracy
let spin_sleeper = spin_sleep::SpinSleeper::new(100_000);

// Sleep for 1.01255 seconds, this will:
//  - thread:sleep for 1.01245 seconds, ie 100μs less than the requested duration
//  - spin until total 1.01255 seconds have elapsed
spin_sleeper.sleep(Duration::new(1, 12_550_000));

Sleep can also requested in f64 seconds or u64 nanoseconds (useful when used with time crate)


OS-specific default accuracy settings should be good enough for most cases.

let sleeper = SpinSleeper::default();



Tool for loop rate reporting and control.


Builds LoopHelper.


Accuracy container for spin sleeping. See crate docs.



Puts the current thread to sleep, if duration is long enough, then spins until the specified nanosecond duration has elapsed.

Type Definitions


Marker alias to show the meaning of a u64 in certain methods.


Marker alias to show the meaning of a f64 in certain methods.


Marker alias to show the meaning of a f64 in certain methods.


Marker alias to show the meaning of a u32 in certain methods.