#sleep #spin #accurate #accuracy #native #thread #far

spin_sleep

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

14 releases (5 stable)

1.2.1 Aug 7, 2024
1.2.0 Jan 5, 2024
1.1.1 Mar 24, 2022
1.0.0 Apr 25, 2020
0.2.1 Jul 10, 2017

#26 in Operating systems

Download history 7072/week @ 2024-07-19 9400/week @ 2024-07-26 9965/week @ 2024-08-02 10811/week @ 2024-08-09 8571/week @ 2024-08-16 10775/week @ 2024-08-23 8766/week @ 2024-08-30 7881/week @ 2024-09-06 5955/week @ 2024-09-13 7615/week @ 2024-09-20 7798/week @ 2024-09-27 8427/week @ 2024-10-04 9903/week @ 2024-10-11 9069/week @ 2024-10-18 11918/week @ 2024-10-25 11298/week @ 2024-11-01

43,377 downloads per month
Used in 169 crates (67 directly)

Apache-2.0

28KB
431 lines

spin_sleep crates.io Documentation

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.

SpinSleeper

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

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

Configure

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)
    .with_spin_strategy(spin_sleep::SpinStrategy::YieldThread);

// Sleep for 1.01255 seconds, this will:
//  - thread:sleep for 1.01245 seconds, i.e., 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 be requested in f64 seconds or u64 nanoseconds (useful when used with time crate)

spin_sleeper.sleep_s(1.01255);
spin_sleeper.sleep_ns(1_012_550_000);

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

let sleeper = SpinSleeper::default();

Windows Accuracy

Windows (>= Windows 10, version 1803) will use a high resolution waitable timer, similar to sleep in rust std >= 1.75.

Earlier versions of Windows have particularly poor accuracy by default (~15ms), spin_sleep will automatically select the best accuracy on Windows generally achieving ~1-2ms native sleep accuracy.

Minimum supported rust compiler

This crate is maintained with latest stable rust.

Dependencies

~0–8MB
~60K SLoC