#sleep #timer #async #async-task #high-resolution #spin #accurate

async-spin-sleep

A crate providing a highly accurate asynchronous timer for multiple async tasks using spin sleep in a single thread

15 releases (4 breaking)

0.5.1 Sep 24, 2023
0.5.0 Aug 8, 2023
0.4.1 Aug 8, 2023
0.4.0 Jun 17, 2023
0.1.1 Jun 11, 2023

#1000 in Hardware support

Download history 3/week @ 2024-11-13 36/week @ 2024-11-20 47/week @ 2024-11-27 45/week @ 2024-12-04 29/week @ 2024-12-11 11/week @ 2024-12-25 10/week @ 2025-01-01 10/week @ 2025-01-22 16/week @ 2025-01-29 15/week @ 2025-02-05 8/week @ 2025-02-12 24/week @ 2025-02-19 28/week @ 2025-02-26

78 downloads per month

MIT license

28KB
413 lines

Async spin sleep

crates.io

한국어

High-resolution asynchronous spin-timer driver

The async-spin-sleep library offers an efficient method to leverage the advantages of a high-resolution timer through a spin loop, catering to numerous asynchronous tasks with minimal overhead.

    use futures::executor::block_on;
    use std::time::{Duration, Instant};

    let (handle, driver) = async_spin_sleep::create();
    std::thread::spawn(driver);

    block_on(async {
        let begin = Instant::now();
        let overslept = handle.sleep_for(Duration::from_millis(100)).await;

        assert!(begin.elapsed() >= Duration::from_millis(100));
        println!("t: {:?}, overslept: {:?}", begin.elapsed(), overslept);
    });

Why is this useful?

Certain applications, such as real-time system implementations on standard PC hardware, media output, or hardware interaction, often demand high-resolution timers. Conventional operating systems like Windows have a timer resolution of around 20ms, which might be insufficient for time-sensitive applications.

A common solution to this challenge is to employ a spin-loop, a busy-wait technique that consumes 100% of a CPU core's time for precise timing measurements. However, when multiple contexts demand similar time precision, simultaneous spin-loop usage can significantly stress the system.

async-spin-sleep alleviates this issue by running a dedicated timer driver, utilizing a spin-loop from a single thread. This thread awakens asynchronous tasks at precise moments. This approach maintains a core fully occupied for a time span shorter than the OS's scheduler resolution, similar to a conventional spin-loop, yet enables sharing of this resource among numerous asynchronous tasks.

Usage

Refer to the documentation.

License

Licensed under either of the following:

Dependencies

~1.5–7MB
~47K SLoC