use hdrhistogram::Histogram;
pub struct FrameStats {
histogram: Histogram<u64>,
}
impl FrameStats {
pub fn new() -> Self {
Self {
histogram: Histogram::new(3).unwrap(),
}
}
pub fn record_ns(&mut self, ns: u64) {
self.histogram.record(ns).unwrap();
}
pub fn count(&self) -> u64 {
self.histogram.len()
}
pub fn p50_ns(&self) -> u64 {
self.histogram.value_at_quantile(0.5)
}
pub fn p95_ns(&self) -> u64 {
self.histogram.value_at_quantile(0.95)
}
pub fn p99_ns(&self) -> u64 {
self.histogram.value_at_quantile(0.99)
}
pub fn mean_ns(&self) -> f64 {
self.histogram.mean()
}
pub fn clear(&mut self) {
self.histogram.reset();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frame_stats_percentiles() {
let mut s = FrameStats::new();
for i in 1..=1000u64 {
s.record_ns(i * 1_000);
}
assert!((490_000..=510_000).contains(&s.p50_ns()));
assert!((980_000..=1_000_000).contains(&s.p99_ns()));
}
}