diff --git a/examples/latency/Cargo.toml b/examples/latency/Cargo.toml new file mode 100644 index 0000000..b7471c6 --- /dev/null +++ b/examples/latency/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "latency" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +num_cpus = "1.13.1" +rand = "0.8.4" +spin_sleep = { path = "../.." } diff --git a/examples/latency/src/main.rs b/examples/latency/src/main.rs new file mode 100644 index 0000000..d3ce461 --- /dev/null +++ b/examples/latency/src/main.rs @@ -0,0 +1,30 @@ +use std::time::{Duration, Instant}; + +use rand::Rng; + +fn main() { + let interval = Duration::from_millis(15); + + let cpus = num_cpus::get(); + let spinners: Vec<_> = (0..cpus).map(|_| { + std::thread::spawn(|| { + let mut rng = rand::thread_rng(); + // Run a lottery instead of boring infinite loop so that it doesn't get misoptimized + while rng.gen::() > 0 {} + }) + }).collect(); + + let mut i = 0; + let mut sum = Duration::default(); + loop { + let now = Instant::now(); + let deadline = now + interval; + spin_sleep::sleep(interval); + sum += Instant::now() - deadline; + i += 1; + if i % 100 == 0 { + dbg!(sum / 100); + sum = Duration::default(); + } + } +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 404bb34..a9e4295 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -148,6 +148,7 @@ impl SpinSleeper { // spin the rest of the duration while start.elapsed() < duration { thread::yield_now(); + // std::hint::spin_loop(); } }