| 1 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
// file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 4 |
|
| 5 |
use std::collections::HashMap; |
| 6 |
|
| 7 |
use malloc_size_of_derive::MallocSizeOf; |
| 8 |
use once_cell::sync::OnceCell; |
| 9 |
use serde::{Deserialize, Serialize}; |
| 10 |
|
| 11 |
use super::{Bucketing, Histogram}; |
| 12 |
|
| 13 |
use crate::util::floating_point_context::FloatingPointContext; |
| 14 |
|
| 15 |
/// Create the possible ranges in an exponential distribution from `min` to `max` with |
| 16 |
/// `bucket_count` buckets. |
| 17 |
/// |
| 18 |
/// This algorithm calculates the bucket sizes using a natural log approach to get `bucket_count` number of buckets, |
| 19 |
/// exponentially spaced between `min` and `max` |
| 20 |
/// |
| 21 |
/// Bucket limits are the minimal bucket value. |
| 22 |
/// That means values in a bucket `i` are `bucket[i] <= value < bucket[i+1]`. |
| 23 |
/// It will always contain an underflow bucket (`< 1`). |
| 24 |
fn exponential_range(min: u64, max: u64, bucket_count: usize) -> Vec<u64> { |
| 25 |
// Set the FPU control flag to the required state within this function |
| 26 |
let _fpc = FloatingPointContext::new(); |
| 27 |
|
| 28 |
let log_max = (max as f64).ln(); |
| 29 |
|
| 30 |
let mut ranges = Vec::with_capacity(bucket_count); |
| 31 |
let mut current = min; |
| 32 |
if current == 0 { |
| 33 |
current = 1; |
| 34 |
} |
| 35 |
|
| 36 |
// undeflow bucket |
| 37 |
ranges.push(0); |
| 38 |
ranges.push(current); |
| 39 |
|
| 40 |
for i in 2..bucket_count { |
| 41 |
let log_current = (current as f64).ln(); |
| 42 |
let log_ratio = (log_max - log_current) / (bucket_count - i) as f64; |
| 43 |
let log_next = log_current + log_ratio; |
| 44 |
let next_value = log_next.exp().round() as u64; |
| 45 |
current = if next_value > current { |
| 46 |
next_value |
| 47 |
} else { |
| 48 |
current + 1 |
| 49 |
}; |
| 50 |
ranges.push(current); |
| 51 |
} |
| 52 |
|
| 53 |
ranges |
| 54 |
} |
| 55 |
|
| 56 |
/// An exponential bucketing algorithm. |
| 57 |
/// |
| 58 |
/// Buckets are pre-computed at instantiation with an exponential distribution from `min` to `max` |
| 59 |
/// and `bucket_count` buckets. |
| 60 |
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, MallocSizeOf)] |
| 61 |
pub struct PrecomputedExponential { |
| 62 |
// Don't serialize the (potentially large) array of ranges, instead compute them on first |
| 63 |
// access. |
| 64 |
#[serde(skip)] |
| 65 |
pub(crate) bucket_ranges: OnceCell<Vec<u64>>, |
| 66 |
pub(crate) min: u64, |
| 67 |
pub(crate) max: u64, |
| 68 |
pub(crate) bucket_count: usize, |
| 69 |
} |
| 70 |
|
| 71 |
impl Bucketing for PrecomputedExponential { |
| 72 |
/// Get the bucket for the sample. |
| 73 |
/// |
| 74 |
/// This uses a binary search to locate the index `i` of the bucket such that: |
| 75 |
/// bucket[i] <= sample < bucket[i+1] |
| 76 |
fn sample_to_bucket_minimum(&self, sample: u64) -> u64 { |
| 77 |
let limit = match self.ranges().binary_search(&sample) { |
| 78 |
// Found an exact match to fit it in |
| 79 |
Ok(i) => i, |
| 80 |
// Sorted it fits after the bucket's limit, therefore it fits into the previous bucket |
| 81 |
Err(i) => i - 1, |
| 82 |
}; |
| 83 |
|
| 84 |
self.ranges()[limit] |
| 85 |
} |
| 86 |
|
| 87 |
fn ranges(&self) -> &[u64] { |
| 88 |
// Create the exponential range on first access. |
| 89 |
self.bucket_ranges |
| 90 |
.get_or_init(|| exponential_range(self.min, self.max, self.bucket_count)) |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
impl Histogram<PrecomputedExponential> { |
| 95 |
/// Creates a histogram with `count` exponential buckets in the range `min` to `max`. |
| 96 |
pub fn exponential( |
| 97 |
min: u64, |
| 98 |
max: u64, |
| 99 |
bucket_count: usize, |
| 100 |
) -> Histogram<PrecomputedExponential> { |
| 101 |
Histogram { |
| 102 |
values: HashMap::new(), |
| 103 |
count: 0, |
| 104 |
sum: 0, |
| 105 |
bucketing: PrecomputedExponential { |
| 106 |
bucket_ranges: OnceCell::new(), |
| 107 |
min, |
| 108 |
max, |
| 109 |
bucket_count, |
| 110 |
}, |
| 111 |
} |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
#[cfg(test)] |
| 116 |
mod test { |
| 117 |
use super::*; |
| 118 |
|
| 119 |
const DEFAULT_BUCKET_COUNT: usize = 100; |
| 120 |
const DEFAULT_RANGE_MIN: u64 = 0; |
| 121 |
const DEFAULT_RANGE_MAX: u64 = 60_000; |
| 122 |
|
| 123 |
#[test] |
| 124 |
fn can_count() { |
| 125 |
let mut hist = Histogram::exponential(1, 500, 10); |
| 126 |
assert!(hist.is_empty()); |
| 127 |
|
| 128 |
for i in 1..=10 { |
| 129 |
hist.accumulate(i); |
| 130 |
} |
| 131 |
|
| 132 |
assert_eq!(10, hist.count()); |
| 133 |
assert_eq!(55, hist.sum()); |
| 134 |
} |
| 135 |
|
| 136 |
#[test] |
| 137 |
fn overflow_values_accumulate_in_the_last_bucket() { |
| 138 |
let mut hist = |
| 139 |
Histogram::exponential(DEFAULT_RANGE_MIN, DEFAULT_RANGE_MAX, DEFAULT_BUCKET_COUNT); |
| 140 |
|
| 141 |
hist.accumulate(DEFAULT_RANGE_MAX + 100); |
| 142 |
assert_eq!(1, hist.values[&DEFAULT_RANGE_MAX]); |
| 143 |
} |
| 144 |
|
| 145 |
#[test] |
| 146 |
fn short_exponential_buckets_are_correct() { |
| 147 |
let test_buckets = vec![0, 1, 2, 3, 5, 9, 16, 29, 54, 100]; |
| 148 |
|
| 149 |
assert_eq!(test_buckets, exponential_range(1, 100, 10)); |
| 150 |
// There's always a zero bucket, so we increase the lower limit. |
| 151 |
assert_eq!(test_buckets, exponential_range(0, 100, 10)); |
| 152 |
} |
| 153 |
|
| 154 |
#[test] |
| 155 |
fn default_exponential_buckets_are_correct() { |
| 156 |
// Hand calculated values using current default range 0 - 60000 and bucket count of 100. |
| 157 |
// NOTE: The final bucket, regardless of width, represents the overflow bucket to hold any |
| 158 |
// values beyond the maximum (in this case the maximum is 60000) |
| 159 |
let test_buckets = vec![ |
| 160 |
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 23, 25, 28, 31, 34, |
| 161 |
38, 42, 46, 51, 56, 62, 68, 75, 83, 92, 101, 111, 122, 135, 149, 164, 181, 200, 221, |
| 162 |
244, 269, 297, 328, 362, 399, 440, 485, 535, 590, 651, 718, 792, 874, 964, 1064, 1174, |
| 163 |
1295, 1429, 1577, 1740, 1920, 2118, 2337, 2579, 2846, 3140, 3464, 3822, 4217, 4653, |
| 164 |
5134, 5665, 6250, 6896, 7609, 8395, 9262, 10219, 11275, 12440, 13726, 15144, 16709, |
| 165 |
18436, 20341, 22443, 24762, 27321, 30144, 33259, 36696, 40488, 44672, 49288, 54381, |
| 166 |
60000, |
| 167 |
]; |
| 168 |
|
| 169 |
assert_eq!( |
| 170 |
test_buckets, |
| 171 |
exponential_range(DEFAULT_RANGE_MIN, DEFAULT_RANGE_MAX, DEFAULT_BUCKET_COUNT) |
| 172 |
); |
| 173 |
} |
| 174 |
|
| 175 |
#[test] |
| 176 |
fn default_buckets_correctly_accumulate() { |
| 177 |
let mut hist = |
| 178 |
Histogram::exponential(DEFAULT_RANGE_MIN, DEFAULT_RANGE_MAX, DEFAULT_BUCKET_COUNT); |
| 179 |
|
| 180 |
for i in &[1, 10, 100, 1000, 10000] { |
| 181 |
hist.accumulate(*i); |
| 182 |
} |
| 183 |
|
| 184 |
assert_eq!(11111, hist.sum()); |
| 185 |
assert_eq!(5, hist.count()); |
| 186 |
|
| 187 |
assert_eq!(None, hist.values.get(&0)); // underflow is empty |
| 188 |
assert_eq!(1, hist.values[&1]); // bucket_ranges[1] = 1 |
| 189 |
assert_eq!(1, hist.values[&10]); // bucket_ranges[10] = 10 |
| 190 |
assert_eq!(1, hist.values[&92]); // bucket_ranges[33] = 92 |
| 191 |
assert_eq!(1, hist.values[&964]); // bucket_ranges[57] = 964 |
| 192 |
assert_eq!(1, hist.values[&9262]); // bucket_ranges[80] = 9262 |
| 193 |
} |
| 194 |
|
| 195 |
#[test] |
| 196 |
fn accumulate_large_numbers() { |
| 197 |
let mut hist = Histogram::exponential(1, 500, 10); |
| 198 |
|
| 199 |
hist.accumulate(u64::MAX); |
| 200 |
hist.accumulate(u64::MAX); |
| 201 |
|
| 202 |
assert_eq!(2, hist.count()); |
| 203 |
// Saturate before overflowing |
| 204 |
assert_eq!(u64::MAX, hist.sum()); |
| 205 |
assert_eq!(2, hist.values[&500]); |
| 206 |
} |
| 207 |
} |