#sleep #spin #fps


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

12 releases (3 stable)

1.1.1 Mar 24, 2022
1.0.0 Apr 25, 2020
0.3.7 Sep 21, 2018
0.3.6 Jul 12, 2018
0.2.1 Jul 10, 2017

#41 in Operating systems

Download history 3457/week @ 2023-08-16 3242/week @ 2023-08-23 2971/week @ 2023-08-30 3411/week @ 2023-09-06 3819/week @ 2023-09-13 3074/week @ 2023-09-20 3619/week @ 2023-09-27 3568/week @ 2023-10-04 4542/week @ 2023-10-11 4281/week @ 2023-10-18 4542/week @ 2023-10-25 4374/week @ 2023-11-01 4790/week @ 2023-11-08 4905/week @ 2023-11-15 4494/week @ 2023-11-22 3773/week @ 2023-11-29

18,662 downloads per month
Used in 136 crates (53 directly)


351 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.


The 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, 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)


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

let sleeper = SpinSleeper::default();


For controlling & report rates (e.g., game FPS) this crate provides LoopHelper. A SpinSleeper is used to maximise sleeping accuracy.

use spin_sleep::LoopHelper;

let mut loop_helper = LoopHelper::builder()
    .report_interval_s(0.5) // report every half a second
    .build_with_target_rate(250.0); // limit to 250 FPS if possible

let mut current_fps = None;

loop {
    let delta = loop_helper.loop_start(); // or .loop_start_s() for f64 seconds

    // compute_something(delta);

    if let Some(fps) = loop_helper.report_rate() {
        current_fps = Some(fps);

    // render_fps(current_fps);

    loop_helper.loop_sleep(); // sleeps to achieve a 250 FPS rate

Windows Accuracy

Windows has particularly poor accuracy by default (~15ms), spin_sleep will automatically select the best accuracy on Windows generally achieving ~1ms native sleep accuracy (Since 0.3.3).

Minimum supported rust compiler

This crate is maintained with latest stable rust.