use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct RateReporter {
report_period: Duration,
start: Instant,
rate_count: u32,
}
impl RateReporter {
pub fn new(report_period: Duration) -> Self {
Self {
report_period,
start: Instant::now(),
rate_count: 0,
}
}
pub fn increment(&mut self) {
self.rate_count = self.rate_count.saturating_add(1);
}
pub fn report(&mut self) -> Option<f64> {
let now = Instant::now();
let elapsed = now.duration_since(self.start);
if elapsed < self.report_period {
return None;
}
let report = f64::from(self.rate_count) / elapsed.as_secs_f64();
self.rate_count = 0;
self.start = now;
Some(report)
}
pub fn increment_and_report(&mut self) -> Option<f64> {
self.increment();
self.report()
}
pub fn reset(&mut self) {
self.rate_count = 0;
self.start = Instant::now();
}
}