use std::sync::Once;
static RAISED: Once = Once::new();
pub fn raise_resolution() {
RAISED.call_once(|| {
if !sys::raise() {
debug!("cannot raise the timer resolution; timed waits stay coarse");
}
});
}
#[cfg(windows)]
mod sys {
const TIMERR_NOERROR: u32 = 0;
#[link(name = "winmm")]
extern "system" {
fn timeBeginPeriod(period_ms: u32) -> u32;
}
pub fn raise() -> bool {
unsafe { timeBeginPeriod(1) == TIMERR_NOERROR }
}
}
#[cfg(not(windows))]
mod sys {
pub fn raise() -> bool {
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{Duration, Instant};
#[test]
fn short_waits_stay_short() {
raise_resolution();
raise_resolution();
let m = std::sync::Mutex::new(());
let cv = std::sync::Condvar::new();
let mut waits: Vec<Duration> = (0..20)
.map(|_| {
let g = m.lock().unwrap();
let t = Instant::now();
let _ = cv.wait_timeout(g, Duration::from_millis(1)).unwrap();
t.elapsed()
})
.collect();
waits.sort();
assert!(waits[10] < Duration::from_millis(12), "{waits:?}");
}
}