1use std::{
2 collections::VecDeque,
3 ops::RangeInclusive,
4 sync::atomic::{AtomicU64, Ordering},
5 time::{Duration, Instant},
6};
7
8use itertools::Itertools;
9
10const N_BUCKETS: usize = 92;
11
12#[derive(Debug)]
30pub struct ExponentialHistogram {
31 buckets: [AtomicU64; N_BUCKETS],
32 sum: AtomicU64,
33}
34
35impl ExponentialHistogram {
36 pub const fn new() -> Self {
38 Self {
39 buckets: [const { AtomicU64::new(0) }; N_BUCKETS],
40 sum: AtomicU64::new(0),
41 }
42 }
43
44 pub fn record(&self, value: impl TryInto<u64>) {
46 if let Ok(value) = value.try_into() {
47 self.buckets[number_to_bucket(value)].fetch_add(1, Ordering::Relaxed);
48 self.sum.fetch_add(value, Ordering::Relaxed);
49 }
50 }
51
52 pub fn record_elapsed(&self, start: Instant) {
55 self.record_duration(start.elapsed());
56 }
57
58 pub fn record_duration(&self, duration: Duration) {
60 self.record(duration.as_micros());
61 }
62
63 pub fn snapshot(&self) -> ExponentialHistogramSnapshot {
65 ExponentialHistogramSnapshot {
66 buckets: self
67 .buckets
68 .iter()
69 .map(|bucket| bucket.load(Ordering::Relaxed))
70 .collect_array()
71 .unwrap(),
72 sum: self.sum.load(Ordering::Relaxed),
73 }
74 }
75
76 pub fn sum(&self) -> u64 {
78 self.sum.load(Ordering::Relaxed)
79 }
80
81 pub fn record_callback<F, T>(&self, f: F) -> T
84 where
85 F: FnOnce() -> T,
86 {
87 let start = Instant::now();
88 let retval = f();
89 self.record_elapsed(start);
90 retval
91 }
92}
93
94impl Default for ExponentialHistogram {
95 fn default() -> Self {
96 Self::new()
97 }
98}
99
100pub struct ExponentialHistogramSnapshot {
101 buckets: [u64; N_BUCKETS],
102 sum: u64,
103}
104
105impl ExponentialHistogramSnapshot {
106 pub fn iter_buckets(&self) -> impl Iterator<Item = Bucket> + use<'_> {
107 self.buckets
108 .iter()
109 .enumerate()
110 .map(|(index, count)| Bucket {
111 range: bucket_to_range(index),
112 count: *count,
113 })
114 }
115 pub fn sum(&self) -> u64 {
116 self.sum
117 }
118
119 pub fn quantile(&self, q: f64) -> Option<u64> {
122 let total: u64 = self.buckets.iter().sum();
123 if total == 0 {
124 return None;
125 }
126 let rank = ((q.clamp(0.0, 1.0) * total as f64).ceil() as u64).clamp(1, total);
127 let mut cumulative = 0u64;
128 for (index, count) in self.buckets.iter().enumerate() {
129 cumulative += *count;
130 if cumulative >= rank {
131 return Some(*bucket_to_range(index).start());
132 }
133 }
134 Some(*bucket_to_range(N_BUCKETS - 1).start())
136 }
137}
138
139pub struct Bucket {
140 pub range: RangeInclusive<u64>,
141 pub count: u64,
142}
143
144fn number_to_bucket(number: u64) -> usize {
145 let bucket = match number {
146 0..10 => number,
148 10..100 => (number - 10) / 10 + 10,
150 100..1000 => (number - 100) / 100 + 19,
152 1000..10_000 => (number - 1000) / 1000 + 28,
154 10_000..100_000 => (number - 10_000) / 10_000 + 37,
156 100_000..1_000_000 => (number - 100_000) / 100_000 + 46,
158 1_000_000..10_000_000 => (number - 1_000_000) / 1_000_000 + 55,
160 10_000_000..100_000_000 => (number - 10_000_000) / 10_000_000 + 64,
162 100_000_000..1_000_000_000 => (number - 100_000_000) / 100_000_000 + 73,
164 1_000_000_000..10_000_000_000 => (number - 1_000_000_000) / 1_000_000_000 + 82,
166 _ => 91,
168 };
169 bucket as usize
170}
171
172fn bucket_to_range(bucket: usize) -> RangeInclusive<u64> {
173 let bucket = bucket as u64;
174 fn bucket_range(index: u64, width: u64) -> RangeInclusive<u64> {
175 let start = (index + 1) * width;
176 let end = start + (width - 1);
177 start..=end
178 }
179 match bucket {
180 0..=9 => bucket..=bucket,
181 10..=18 => bucket_range(bucket - 10, 10),
182 19..=27 => bucket_range(bucket - 19, 100),
183 28..=36 => bucket_range(bucket - 28, 1000),
184 37..=45 => bucket_range(bucket - 37, 10_000),
185 46..=54 => bucket_range(bucket - 46, 100_000),
186 55..=63 => bucket_range(bucket - 55, 1_000_000),
187 64..=72 => bucket_range(bucket - 64, 10_000_000),
188 73..=81 => bucket_range(bucket - 73, 100_000_000),
189 82..=90 => bucket_range(bucket - 82, 1_000_000_000),
190 91 => 1_000_000_001..=u64::MAX,
191 _ => unreachable!(),
192 }
193}
194
195#[derive(Debug)]
201pub struct SlidingHistogram {
202 buckets: [u64; N_BUCKETS],
203 samples: VecDeque<Sample>,
204 sum: u64,
205 max_samples: usize,
206 max_elapsed: Duration,
207}
208
209#[derive(Debug)]
210struct Sample {
211 time: Instant,
212 value: u64,
213}
214
215impl SlidingHistogram {
216 pub const fn new(max_samples: usize, max_elapsed: Duration) -> Self {
220 Self {
221 buckets: [0; N_BUCKETS],
222 samples: VecDeque::new(),
223 sum: 0,
224 max_samples,
225 max_elapsed,
226 }
227 }
228
229 pub fn record(&mut self, value: impl TryInto<u64>) {
231 if let Ok(value) = value.try_into() {
232 if self.samples.len() >= self.max_samples {
233 self.drop_sample();
234 }
235 self.samples.push_back(Sample {
236 time: Instant::now(),
237 value,
238 });
239 self.buckets[number_to_bucket(value)] += 1;
240 self.sum += value;
241 }
242 }
243
244 pub fn record_elapsed(&mut self, start: Instant) {
247 self.record(start.elapsed().as_micros());
248 }
249
250 pub fn snapshot(&mut self) -> ExponentialHistogramSnapshot {
252 if let Some(most_recent) = self.samples.back() {
258 let cutoff = most_recent.time - self.max_elapsed;
259 while self
260 .samples
261 .front()
262 .is_some_and(|sample| sample.time < cutoff)
263 {
264 self.drop_sample();
265 }
266 }
267
268 ExponentialHistogramSnapshot {
269 buckets: self.buckets,
270 sum: self.sum,
271 }
272 }
273
274 pub fn sum(&self) -> u64 {
276 self.sum
277 }
278
279 pub fn record_callback<F, T>(&mut self, f: F) -> T
282 where
283 F: FnOnce() -> T,
284 {
285 let start = Instant::now();
286 let retval = f();
287 self.record_elapsed(start);
288 retval
289 }
290
291 fn drop_sample(&mut self) {
292 let sample = self.samples.pop_front().unwrap();
293 self.buckets[number_to_bucket(sample.value)] -= 1;
294 self.sum -= sample.value;
295 }
296}
297
298#[cfg(test)]
299mod test {
300 use crate::histogram::{ExponentialHistogram, N_BUCKETS, bucket_to_range, number_to_bucket};
301
302 #[test]
303 fn quantile_empty() {
304 let hist = ExponentialHistogram::new();
305 assert_eq!(hist.snapshot().quantile(0.5), None);
306 assert_eq!(hist.snapshot().quantile(0.99), None);
307 }
308
309 #[test]
310 fn quantile_single_sample() {
311 let hist = ExponentialHistogram::new();
312 hist.record(42u64);
313 assert_eq!(hist.snapshot().quantile(0.0), Some(40));
315 assert_eq!(hist.snapshot().quantile(0.5), Some(40));
316 assert_eq!(hist.snapshot().quantile(1.0), Some(40));
317 }
318
319 #[test]
320 fn quantile_all_same_bucket() {
321 let hist = ExponentialHistogram::new();
322 for _ in 0..100 {
323 hist.record(5u64);
324 }
325 assert_eq!(hist.snapshot().quantile(0.5), Some(5));
327 assert_eq!(hist.snapshot().quantile(0.99), Some(5));
328 }
329
330 #[test]
331 fn quantile_known_distribution() {
332 let hist = ExponentialHistogram::new();
333 for _ in 0..99 {
335 hist.record(0u64);
336 }
337 hist.record(950u64);
338 let snap = hist.snapshot();
339 assert_eq!(snap.quantile(0.5), Some(0));
341 assert_eq!(snap.quantile(0.99), Some(0));
343 assert_eq!(snap.quantile(1.0), Some(900));
345 }
346
347 #[test]
348 fn buckets() {
349 let mut base = 1;
350 while base <= u64::MAX / 10 {
351 for multiple in 1..10 {
352 let number = base * multiple;
353 for number in [number - 1, number, number + 1] {
354 let bucket = number_to_bucket(number);
355 assert!((0..N_BUCKETS).contains(&bucket));
356 let bucket_range = bucket_to_range(bucket);
357 assert!(bucket_range.contains(&number));
358 }
359 }
360 base *= 10;
361 }
362 }
363}