| 1 | use core::sync::atomic::{AtomicU32, AtomicU64}; |
| 2 | |
| 3 | use crate::config::Config; |
| 4 | use crate::{AtomicCount, Count, Error, Histogram, Histogram32}; |
| 5 | |
| 6 | macro_rules! define_atomic_histogram { |
| 7 | ($name:ident, $count:ty, $atomic:ty, $hist:ident) => { |
| 8 | /// A histogram that uses atomic counters for each bucket. |
| 9 | /// |
| 10 | /// Unlike the non-atomic variant, it cannot be used directly to report |
| 11 | /// percentiles. Instead, a snapshot must be taken which captures the |
| 12 | /// state of the histogram at a point in time. |
| 13 | pub struct $name { |
| 14 | pub(crate) config: Config, |
| 15 | pub(crate) buckets: Box<[$atomic]>, |
| 16 | } |
| 17 | |
| 18 | impl $name { |
| 19 | /// Construct a new atomic histogram from the provided parameters. |
| 20 | /// See [`crate::Config`] for the meaning of the parameters. |
| 21 | pub fn new(grouping_power: u8, max_value_power: u8) -> Result<Self, Error> { |
| 22 | let config = Config::new(grouping_power, max_value_power)?; |
| 23 | Ok(Self::with_config(&config)) |
| 24 | } |
| 25 | |
| 26 | /// Creates a new atomic histogram using a provided [`crate::Config`]. |
| 27 | pub fn with_config(config: &Config) -> Self { |
| 28 | let mut buckets = Vec::with_capacity(config.total_buckets()); |
| 29 | buckets.resize_with(config.total_buckets(), || { |
| 30 | <$atomic as AtomicCount>::new(<$count as Count>::ZERO) |
| 31 | }); |
| 32 | Self { |
| 33 | config: *config, |
| 34 | buckets: buckets.into(), |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /// Increment the bucket that contains `value` by one. |
| 39 | pub fn increment(&self, value: u64) -> Result<(), Error> { |
| 40 | self.add(value, <$count as Count>::ONE) |
| 41 | } |
| 42 | |
| 43 | /// Add `count` to the bucket that contains `value`. |
| 44 | pub fn add(&self, value: u64, count: $count) -> Result<(), Error> { |
| 45 | let index = self.config.value_to_index(value)?; |
| 46 | self.buckets[index].fetch_add_relaxed(count); |
| 47 | Ok(()) |
| 48 | } |
| 49 | |
| 50 | /// Returns the bucket configuration of the histogram. |
| 51 | pub fn config(&self) -> Config { |
| 52 | self.config |
| 53 | } |
| 54 | |
| 55 | /// Read the bucket values into a new non-atomic histogram snapshot. |
| 56 | pub fn load(&self) -> $hist { |
| 57 | let buckets: Vec<$count> = self.buckets.iter().map(|b| b.load_relaxed()).collect(); |
| 58 | $hist { |
| 59 | config: self.config, |
| 60 | buckets: buckets.into(), |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | impl std::fmt::Debug for $name { |
| 66 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 67 | f.debug_struct(stringify!($name)) |
| 68 | .field("config", &self.config) |
| 69 | .finish() |
| 70 | } |
| 71 | } |
| 72 | }; |
| 73 | } |
| 74 | |
| 75 | define_atomic_histogram!(AtomicHistogram, u64, AtomicU64, Histogram); |
| 76 | define_atomic_histogram!(AtomicHistogram32, u32, AtomicU32, Histogram32); |
| 77 | |
| 78 | // NOTE: once stabilized, `target_has_atomic_load_store` is more correct. |
| 79 | // https://github.com/rust-lang/rust/issues/94039 |
| 80 | #[cfg(target_has_atomic = "64")] |
| 81 | impl AtomicHistogram { |
| 82 | /// Drains the bucket values into a new `Histogram`. |
| 83 | /// |
| 84 | /// Unlike [`load`](AtomicHistogram::load), this method resets all bucket |
| 85 | /// values to zero. Uses [`AtomicU64::swap`] under the hood and is |
| 86 | /// available only on platforms that support 64-bit atomics. |
| 87 | pub fn drain(&self) -> Histogram { |
| 88 | let buckets: Vec<u64> = self.buckets.iter().map(|b| b.swap_relaxed(0)).collect(); |
| 89 | Histogram { |
| 90 | config: self.config, |
| 91 | buckets: buckets.into(), |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | #[cfg(target_has_atomic = "32")] |
| 97 | impl AtomicHistogram32 { |
| 98 | /// Drains the bucket values into a new `Histogram32`. Resets all |
| 99 | /// buckets to zero. Available only on platforms that support 32-bit |
| 100 | /// atomics (more widely supported than 64-bit). |
| 101 | pub fn drain(&self) -> Histogram32 { |
| 102 | let buckets: Vec<u32> = self.buckets.iter().map(|b| b.swap_relaxed(0)).collect(); |
| 103 | Histogram32 { |
| 104 | config: self.config, |
| 105 | buckets: buckets.into(), |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | #[cfg(test)] |
| 111 | mod tests { |
| 112 | use crate::*; |
| 113 | |
| 114 | #[cfg(target_pointer_width = "64")] |
| 115 | #[test] |
| 116 | fn size() { |
| 117 | assert_eq!(std::mem::size_of::<AtomicHistogram>(), 48); |
| 118 | } |
| 119 | |
| 120 | #[cfg(target_has_atomic = "64")] |
| 121 | #[test] |
| 122 | /// Tests that drain properly resets buckets to 0. |
| 123 | fn drain() { |
| 124 | let histogram = AtomicHistogram::new(7, 64).unwrap(); |
| 125 | for i in 0..=100 { |
| 126 | let _ = histogram.increment(i); |
| 127 | } |
| 128 | let snapshot = histogram.drain(); |
| 129 | let result = snapshot.quantile(0.50).unwrap().unwrap(); |
| 130 | assert_eq!( |
| 131 | result.get(&Quantile::new(0.50).unwrap()), |
| 132 | Some(&Bucket { |
| 133 | count: 1, |
| 134 | range: 50..=50, |
| 135 | }) |
| 136 | ); |
| 137 | histogram.increment(1000).unwrap(); |
| 138 | let snapshot = histogram.drain(); |
| 139 | let result = snapshot.quantile(0.50).unwrap().unwrap(); |
| 140 | assert_eq!( |
| 141 | result.get(&Quantile::new(0.50).unwrap()), |
| 142 | Some(&Bucket { |
| 143 | count: 1, |
| 144 | range: 1000..=1003, |
| 145 | }) |
| 146 | ); |
| 147 | } |
| 148 | |
| 149 | #[test] |
| 150 | fn quantiles() { |
| 151 | let histogram = AtomicHistogram::new(7, 64).unwrap(); |
| 152 | let qs = [0.25, 0.50, 0.75, 0.90, 0.99]; |
| 153 | |
| 154 | // check empty |
| 155 | assert_eq!(histogram.load().quantiles(&qs).unwrap(), None); |
| 156 | assert_eq!(histogram.load().quantile(0.5).unwrap(), None); |
| 157 | |
| 158 | // populate and check min/max |
| 159 | for i in 0..=100 { |
| 160 | let _ = histogram.increment(i); |
| 161 | let result = histogram.load().quantile(0.0).unwrap().unwrap(); |
| 162 | assert_eq!( |
| 163 | result.get(&Quantile::new(0.0).unwrap()), |
| 164 | Some(&Bucket { |
| 165 | count: 1, |
| 166 | range: 0..=0, |
| 167 | }) |
| 168 | ); |
| 169 | let result = histogram.load().quantile(1.0).unwrap().unwrap(); |
| 170 | assert_eq!( |
| 171 | result.get(&Quantile::new(1.0).unwrap()), |
| 172 | Some(&Bucket { |
| 173 | count: 1, |
| 174 | range: i..=i, |
| 175 | }) |
| 176 | ); |
| 177 | } |
| 178 | |
| 179 | for q in qs { |
| 180 | let result = histogram.load().quantile(q).unwrap().unwrap(); |
| 181 | let bucket = result.get(&Quantile::new(q).unwrap()).unwrap(); |
| 182 | assert_eq!(bucket.end(), (q * 100.0) as u64); |
| 183 | } |
| 184 | |
| 185 | let result = histogram.load().quantile(0.999).unwrap().unwrap(); |
| 186 | assert_eq!( |
| 187 | result.get(&Quantile::new(0.999).unwrap()).unwrap().end(), |
| 188 | 100 |
| 189 | ); |
| 190 | |
| 191 | assert_eq!( |
| 192 | histogram.load().quantiles(&[-1.0]), |
| 193 | Err(Error::InvalidQuantile) |
| 194 | ); |
| 195 | assert_eq!( |
| 196 | histogram.load().quantiles(&[1.01]), |
| 197 | Err(Error::InvalidQuantile) |
| 198 | ); |
| 199 | |
| 200 | let result = histogram |
| 201 | .load() |
| 202 | .quantiles(&[0.5, 0.9, 0.99, 0.999]) |
| 203 | .unwrap() |
| 204 | .unwrap(); |
| 205 | let values: Vec<(f64, u64)> = result |
| 206 | .entries() |
| 207 | .iter() |
| 208 | .map(|(q, b)| (q.as_f64(), b.end())) |
| 209 | .collect(); |
| 210 | assert_eq!(values, vec![(0.5, 50), (0.9, 90), (0.99, 99), (0.999, 100)]); |
| 211 | |
| 212 | let _ = histogram.increment(1024); |
| 213 | let result = histogram.load().quantile(0.999).unwrap().unwrap(); |
| 214 | assert_eq!( |
| 215 | result.get(&Quantile::new(0.999).unwrap()), |
| 216 | Some(&Bucket { |
| 217 | count: 1, |
| 218 | range: 1024..=1031, |
| 219 | }) |
| 220 | ); |
| 221 | } |
| 222 | |
| 223 | #[cfg(target_pointer_width = "64")] |
| 224 | #[test] |
| 225 | fn size_u32() { |
| 226 | assert_eq!(std::mem::size_of::<AtomicHistogram32>(), 48); |
| 227 | } |
| 228 | |
| 229 | #[cfg(target_has_atomic = "32")] |
| 230 | #[test] |
| 231 | fn drain_u32() { |
| 232 | let h = AtomicHistogram32::new(7, 64).unwrap(); |
| 233 | for v in 0..=100u64 { |
| 234 | h.increment(v).unwrap(); |
| 235 | } |
| 236 | let snap = h.drain(); |
| 237 | let result = snap.quantile(0.5).unwrap().unwrap(); |
| 238 | let q = Quantile::new(0.5).unwrap(); |
| 239 | assert_eq!(result.get(&q).unwrap().end(), 50); |
| 240 | } |
| 241 | } |