use std::sync::atomic::{AtomicU64, Ordering};
pub const LATENCY_BUCKETS_NS: &[u64] = &[
100,
250,
500,
1_000,
2_500,
5_000,
10_000,
25_000,
50_000,
100_000,
250_000,
500_000,
1_000_000,
2_500_000,
5_000_000,
10_000_000,
25_000_000,
50_000_000,
100_000_000,
250_000_000,
500_000_000,
1_000_000_000,
2_500_000_000,
5_000_000_000,
10_000_000_000,
];
pub const SIZE_BUCKETS_BYTES: &[u64] = &[
64, 256, 1_024, 4_096, 16_384, 65_536, 262_144, 1_048_576, 4_194_304, 16_777_216,
];
pub struct Histogram {
buckets: Box<[AtomicU64]>,
sum: AtomicU64,
count: AtomicU64,
min: AtomicU64,
max: AtomicU64,
boundaries: &'static [u64],
}
impl Histogram {
pub fn new(boundaries: &'static [u64]) -> Self {
debug_assert!(
!boundaries.is_empty(),
"histogram boundaries must not be empty"
);
debug_assert!(
boundaries.windows(2).all(|w| w[0] < w[1]),
"histogram boundaries must be sorted ascending"
);
let bucket_count = boundaries.len() + 1; let mut buckets = Vec::with_capacity(bucket_count);
for _ in 0..bucket_count {
buckets.push(AtomicU64::new(0));
}
Self {
buckets: buckets.into_boxed_slice(),
sum: AtomicU64::new(0),
count: AtomicU64::new(0),
min: AtomicU64::new(u64::MAX),
max: AtomicU64::new(0),
boundaries,
}
}
#[inline]
pub fn record(&self, value: u64) {
let bucket_idx = match self.boundaries.binary_search(&value) {
Ok(i) => i,
Err(i) => i,
};
self.buckets[bucket_idx].fetch_add(1, Ordering::Relaxed);
self.sum.fetch_add(value, Ordering::Relaxed);
self.count.fetch_add(1, Ordering::Relaxed);
let mut current_min = self.min.load(Ordering::Relaxed);
while value < current_min {
match self.min.compare_exchange_weak(
current_min,
value,
Ordering::Relaxed,
Ordering::Relaxed,
) {
Ok(_) => break,
Err(actual) => current_min = actual,
}
}
let mut current_max = self.max.load(Ordering::Relaxed);
while value > current_max {
match self.max.compare_exchange_weak(
current_max,
value,
Ordering::Relaxed,
Ordering::Relaxed,
) {
Ok(_) => break,
Err(actual) => current_max = actual,
}
}
}
#[inline]
pub fn count(&self) -> u64 {
self.count.load(Ordering::Relaxed)
}
#[inline]
pub fn sum(&self) -> u64 {
self.sum.load(Ordering::Relaxed)
}
#[inline]
pub fn min(&self) -> u64 {
self.min.load(Ordering::Relaxed)
}
#[inline]
pub fn max(&self) -> u64 {
self.max.load(Ordering::Relaxed)
}
pub fn mean(&self) -> f64 {
let c = self.count();
if c == 0 {
return 0.0;
}
self.sum() as f64 / c as f64
}
pub fn snapshot(&self) -> HistogramSnapshot {
let counts: Vec<u64> = self
.buckets
.iter()
.map(|b| b.load(Ordering::Relaxed))
.collect();
HistogramSnapshot {
boundaries: self.boundaries,
counts,
total_count: self.count(),
sum: self.sum(),
min: self.min(),
max: self.max(),
}
}
pub fn reset(&self) {
for bucket in self.buckets.iter() {
bucket.store(0, Ordering::Relaxed);
}
self.sum.store(0, Ordering::Relaxed);
self.count.store(0, Ordering::Relaxed);
self.min.store(u64::MAX, Ordering::Relaxed);
self.max.store(0, Ordering::Relaxed);
}
pub fn boundaries(&self) -> &'static [u64] {
self.boundaries
}
}
impl std::fmt::Debug for Histogram {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Histogram")
.field("count", &self.count())
.field("sum", &self.sum())
.field("min", &self.min())
.field("max", &self.max())
.field("buckets", &self.boundaries.len())
.finish()
}
}
#[derive(Clone, Debug)]
pub struct HistogramSnapshot {
pub boundaries: &'static [u64],
pub counts: Vec<u64>,
pub total_count: u64,
pub sum: u64,
pub min: u64,
pub max: u64,
}
impl HistogramSnapshot {
pub fn percentile(&self, percentile: f64) -> u64 {
debug_assert!(
(0.0..=100.0).contains(&percentile),
"percentile must be in [0.0, 100.0], got {percentile}"
);
if self.total_count == 0 {
return 0;
}
let target = (percentile / 100.0 * self.total_count as f64).ceil() as u64;
let target = target.max(1);
let mut cumulative: u64 = 0;
for (i, &count) in self.counts.iter().enumerate() {
cumulative += count;
if cumulative >= target {
let lower = if i == 0 { 0 } else { self.boundaries[i - 1] };
let upper = if i < self.boundaries.len() {
self.boundaries[i]
} else {
self.max
};
if count == 0 {
return upper;
}
let within_bucket = cumulative - target;
let fraction = 1.0 - (within_bucket as f64 / count as f64);
let value = lower as f64 + fraction * (upper - lower) as f64;
return value as u64;
}
}
self.max
}
pub fn mean(&self) -> f64 {
if self.total_count == 0 {
0.0
} else {
self.sum as f64 / self.total_count as f64
}
}
}
#[cfg(test)]
mod tests {
use super::*;
static TEST_BUCKETS: &[u64] = &[10, 50, 100, 500, 1000];
#[test]
fn test_histogram_new() {
let h = Histogram::new(TEST_BUCKETS);
assert_eq!(h.count(), 0);
assert_eq!(h.sum(), 0);
assert_eq!(h.min(), u64::MAX);
assert_eq!(h.max(), 0);
}
#[test]
fn test_histogram_record_single() {
let h = Histogram::new(TEST_BUCKETS);
h.record(25);
assert_eq!(h.count(), 1);
assert_eq!(h.sum(), 25);
assert_eq!(h.min(), 25);
assert_eq!(h.max(), 25);
}
#[test]
fn test_histogram_record_into_first_bucket() {
let h = Histogram::new(TEST_BUCKETS);
h.record(5);
let snap = h.snapshot();
assert_eq!(snap.counts[0], 1); }
#[test]
fn test_histogram_record_at_boundary() {
let h = Histogram::new(TEST_BUCKETS);
h.record(10); let snap = h.snapshot();
assert_eq!(snap.counts[0], 1);
}
#[test]
fn test_histogram_record_into_overflow() {
let h = Histogram::new(TEST_BUCKETS);
h.record(5000); let snap = h.snapshot();
let overflow_idx = TEST_BUCKETS.len();
assert_eq!(snap.counts[overflow_idx], 1);
}
#[test]
fn test_histogram_multiple_records() {
let h = Histogram::new(TEST_BUCKETS);
for v in [5, 25, 75, 250, 750, 5000] {
h.record(v);
}
assert_eq!(h.count(), 6);
assert_eq!(h.sum(), 5 + 25 + 75 + 250 + 750 + 5000);
assert_eq!(h.min(), 5);
assert_eq!(h.max(), 5000);
}
#[test]
fn test_histogram_reset() {
let h = Histogram::new(TEST_BUCKETS);
h.record(100);
h.record(200);
h.reset();
assert_eq!(h.count(), 0);
assert_eq!(h.sum(), 0);
}
#[test]
fn test_histogram_mean() {
let h = Histogram::new(TEST_BUCKETS);
h.record(100);
h.record(200);
h.record(300);
assert!((h.mean() - 200.0).abs() < 0.01);
}
#[test]
fn test_histogram_mean_empty() {
let h = Histogram::new(TEST_BUCKETS);
assert_eq!(h.mean(), 0.0);
}
#[test]
fn test_histogram_snapshot_percentile_p50() {
let h = Histogram::new(TEST_BUCKETS);
for v in 1..=100 {
h.record(v);
}
let snap = h.snapshot();
let p50 = snap.percentile(50.0);
assert!(p50 > 0 && p50 <= 100, "p50 was {p50}");
}
#[test]
fn test_histogram_snapshot_percentile_empty() {
let h = Histogram::new(TEST_BUCKETS);
let snap = h.snapshot();
assert_eq!(snap.percentile(50.0), 0);
}
#[test]
fn test_histogram_concurrent_records() {
use std::sync::Arc;
use std::thread;
let h = Arc::new(Histogram::new(TEST_BUCKETS));
let mut handles = Vec::new();
for _ in 0..8 {
let h = Arc::clone(&h);
handles.push(thread::spawn(move || {
for v in 0..1000 {
h.record(v);
}
}));
}
for handle in handles {
handle.join().unwrap();
}
assert_eq!(h.count(), 8000);
}
#[test]
fn test_latency_buckets_sorted() {
assert!(LATENCY_BUCKETS_NS.windows(2).all(|w| w[0] < w[1]));
}
#[test]
fn test_size_buckets_sorted() {
assert!(SIZE_BUCKETS_BYTES.windows(2).all(|w| w[0] < w[1]));
}
}