Debian Codegraph @

third_party/rust/glean-core/src/histogram/linear.rs

raw
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::cmp;
6 use std::collections::HashMap;
7
8 use malloc_size_of_derive::MallocSizeOf;
9 use once_cell::sync::OnceCell;
10 use serde::{Deserialize, Serialize};
11
12 use super::{Bucketing, Histogram};
13
14 /// Create the possible ranges in a linear distribution from `min` to `max` with
15 /// `bucket_count` buckets.
16 ///
17 /// This algorithm calculates `bucket_count` number of buckets of equal sizes between `min` and `max`.
18 ///
19 /// Bucket limits are the minimal bucket value.
20 /// That means values in a bucket `i` are `bucket[i] <= value < bucket[i+1]`.
21 /// It will always contain an underflow bucket (`< 1`).
22 fn linear_range(min: u64, max: u64, count: usize) -> Vec<u64> {
23 let mut ranges = Vec::with_capacity(count);
24 ranges.push(0);
25
26 let min = cmp::max(1, min);
27 let count = count as u64;
28 for i in 1..count {
29 let range = (min * (count - 1 - i) + max * (i - 1)) / (count - 2);
30 ranges.push(range);
31 }
32
33 ranges
34 }
35
36 /// A linear bucketing algorithm.
37 ///
38 /// Buckets are pre-computed at instantiation with a linear distribution from `min` to `max`
39 /// and `bucket_count` buckets.
40 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, MallocSizeOf)]
41 pub struct PrecomputedLinear {
42 // Don't serialize the (potentially large) array of ranges, instead compute them on first
43 // access.
44 #[serde(skip)]
45 pub(crate) bucket_ranges: OnceCell<Vec<u64>>,
46 pub(crate) min: u64,
47 pub(crate) max: u64,
48 pub(crate) bucket_count: usize,
49 }
50
51 impl Bucketing for PrecomputedLinear {
52 /// Get the bucket for the sample.
53 ///
54 /// This uses a binary search to locate the index `i` of the bucket such that:
55 /// bucket[i] <= sample < bucket[i+1]
56 fn sample_to_bucket_minimum(&self, sample: u64) -> u64 {
57 let limit = match self.ranges().binary_search(&sample) {
58 // Found an exact match to fit it in
59 Ok(i) => i,
60 // Sorted it fits after the bucket's limit, therefore it fits into the previous bucket
61 Err(i) => i - 1,
62 };
63
64 self.ranges()[limit]
65 }
66
67 fn ranges(&self) -> &[u64] {
68 // Create the linear range on first access.
69 self.bucket_ranges
70 .get_or_init(|| linear_range(self.min, self.max, self.bucket_count))
71 }
72 }
73
74 impl Histogram<PrecomputedLinear> {
75 /// Creates a histogram with `bucket_count` linear buckets in the range `min` to `max`.
76 pub fn linear(min: u64, max: u64, bucket_count: usize) -> Histogram<PrecomputedLinear> {
77 Histogram {
78 values: HashMap::new(),
79 count: 0,
80 sum: 0,
81 bucketing: PrecomputedLinear {
82 bucket_ranges: OnceCell::new(),
83 min,
84 max,
85 bucket_count,
86 },
87 }
88 }
89 }
90
91 #[cfg(test)]
92 mod test {
93 use super::*;
94
95 const DEFAULT_BUCKET_COUNT: usize = 100;
96 const DEFAULT_RANGE_MIN: u64 = 0;
97 const DEFAULT_RANGE_MAX: u64 = 100;
98
99 #[test]
100 fn can_count() {
101 let mut hist = Histogram::linear(1, 500, 10);
102 assert!(hist.is_empty());
103
104 for i in 1..=10 {
105 hist.accumulate(i);
106 }
107
108 assert_eq!(10, hist.count());
109 assert_eq!(55, hist.sum());
110 }
111
112 #[test]
113 fn overflow_values_accumulate_in_the_last_bucket() {
114 let mut hist =
115 Histogram::linear(DEFAULT_RANGE_MIN, DEFAULT_RANGE_MAX, DEFAULT_BUCKET_COUNT);
116
117 hist.accumulate(DEFAULT_RANGE_MAX + 100);
118 assert_eq!(1, hist.values[&DEFAULT_RANGE_MAX]);
119 }
120
121 #[test]
122 fn short_linear_buckets_are_correct() {
123 let test_buckets = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 10];
124
125 assert_eq!(test_buckets, linear_range(1, 10, 10));
126 // There's always a zero bucket, so we increase the lower limit.
127 assert_eq!(test_buckets, linear_range(0, 10, 10));
128 }
129
130 #[test]
131 fn long_linear_buckets_are_correct() {
132 // Hand calculated values using current default range 0 - 60000 and bucket count of 100.
133 // NOTE: The final bucket, regardless of width, represents the overflow bucket to hold any
134 // values beyond the maximum (in this case the maximum is 60000)
135 let test_buckets = vec![
136 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
137 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
138 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
139 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
140 90, 91, 92, 93, 94, 95, 96, 97, 98, 100,
141 ];
142
143 assert_eq!(
144 test_buckets,
145 linear_range(DEFAULT_RANGE_MIN, DEFAULT_RANGE_MAX, DEFAULT_BUCKET_COUNT)
146 );
147 }
148
149 #[test]
150 fn default_buckets_correctly_accumulate() {
151 let mut hist =
152 Histogram::linear(DEFAULT_RANGE_MIN, DEFAULT_RANGE_MAX, DEFAULT_BUCKET_COUNT);
153
154 for i in &[1, 10, 100, 1000, 10000] {
155 hist.accumulate(*i);
156 }
157
158 assert_eq!(11111, hist.sum());
159 assert_eq!(5, hist.count());
160
161 assert_eq!(None, hist.values.get(&0));
162 assert_eq!(1, hist.values[&1]);
163 assert_eq!(1, hist.values[&10]);
164 assert_eq!(3, hist.values[&100]);
165 }
166
167 #[test]
168 fn accumulate_large_numbers() {
169 let mut hist = Histogram::linear(1, 500, 10);
170
171 hist.accumulate(u64::MAX);
172 hist.accumulate(u64::MAX);
173
174 assert_eq!(2, hist.count());
175 // Saturate before overflowing
176 assert_eq!(u64::MAX, hist.sum());
177 assert_eq!(2, hist.values[&500]);
178 }
179 }