Skip to content

Instantly share code, notes, and snippets.

@leo60228
Created February 27, 2021 21:39
Show Gist options
  • Save leo60228/07ceec72e0bfec67ab4a61d143bccee2 to your computer and use it in GitHub Desktop.
Save leo60228/07ceec72e0bfec67ab4a61d143bccee2 to your computer and use it in GitHub Desktop.
use rayon::prelude::*;
use std::sync::Mutex;
use std::time::{Duration, Instant};
#[derive(Clone, Debug)]
pub struct IntervalTimer {
pub period: Duration,
pub delta: Instant,
}
impl IntervalTimer {
pub fn new(period: Duration) -> Self {
let delta = Instant::now();
Self { period, delta }
}
/// Returns true if the interval between calls has exceeded the period
pub fn ready(&mut self) -> bool {
if self.delta.elapsed() < self.period {
false
} else {
self.delta = self.delta + self.period;
true
}
}
}
fn main() {
let v: Vec<_> = std::iter::repeat(vec![1, 2, 3])
.flatten()
.take(30)
.collect();
let timer = Mutex::new(IntervalTimer::new(Duration::from_millis(20)));
v.into_par_iter().for_each(|x| {
for _ in 0..x {
while !timer.lock().unwrap().ready() {}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment