Skip to content

Commit

Permalink
A crude benchmark to compare spin loop hint to yield
Browse files Browse the repository at this point in the history
  • Loading branch information
ishitatsuyuki committed Feb 8, 2022
1 parent a68f8a8 commit c59197c
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
11 changes: 11 additions & 0 deletions examples/latency/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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 = "../.." }
30 changes: 30 additions & 0 deletions examples/latency/src/main.rs
Original file line number Diff line number Diff line change
@@ -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::<u64>() > 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();
}
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ impl SpinSleeper {
// spin the rest of the duration
while start.elapsed() < duration {
thread::yield_now();
// std::hint::spin_loop();
}
}

Expand Down

0 comments on commit c59197c

Please sign in to comment.