| 1 | # histogram |
| 2 | |
| 3 | A collection of histogram data structures for Rust, providing standard, atomic, |
| 4 | and sparse variants. Like HDRHistogram, values are stored in quantized buckets, |
| 5 | but the bucket construction and indexing algorithm are modified for fast |
| 6 | increments and lookups. |
| 7 | |
| 8 | ## Getting Started |
| 9 | |
| 10 | ``` |
| 11 | cargo add histogram |
| 12 | ``` |
| 13 | |
| 14 | ## Usage |
| 15 | |
| 16 | ```rust |
| 17 | use histogram::{Histogram, Quantile}; |
| 18 | |
| 19 | // Create a histogram with grouping power 7 and max value power 64. |
| 20 | let mut histogram = Histogram::new(7, 64).unwrap(); |
| 21 | |
| 22 | // Record some values. |
| 23 | for i in 1..=100 { |
| 24 | histogram.increment(i).unwrap(); |
| 25 | } |
| 26 | |
| 27 | // Query quantiles using the 0.0..=1.0 scale. |
| 28 | let r50 = histogram.quantile(0.5).unwrap().unwrap(); |
| 29 | let r99 = histogram.quantile(0.99).unwrap().unwrap(); |
| 30 | // quantile() returns Result<Option<QuantilesResult>, Error> |
| 31 | // outer unwrap: quantile value is valid |
| 32 | // inner unwrap: histogram is non-empty |
| 33 | |
| 34 | let median = r50.get(&Quantile::new(0.5).unwrap()).unwrap(); |
| 35 | let p99 = r99.get(&Quantile::new(0.99).unwrap()).unwrap(); |
| 36 | |
| 37 | println!("median: {}", median.end()); |
| 38 | println!("p99: {}", p99.end()); |
| 39 | ``` |
| 40 | |
| 41 | ## Histogram Types |
| 42 | |
| 43 | - **Histogram** -- Standard histogram with plain 64-bit counters. Best for |
| 44 | single-threaded use. |
| 45 | - **AtomicHistogram** -- Uses atomic 64-bit counters, allowing concurrent |
| 46 | recording from multiple threads. Take a snapshot via `load()` or `drain()` |
| 47 | to query percentiles. |
| 48 | - **SparseHistogram** -- Columnar representation that only stores non-zero |
| 49 | buckets. Ideal for serialization and storage when most buckets are empty. |
| 50 | - **CumulativeROHistogram** -- Read-only histogram with cumulative counts for |
| 51 | fast O(log n) quantile queries via binary search. |
| 52 | |
| 53 | All four types ship with a `*32` sibling (`Histogram32`, `AtomicHistogram32`, |
| 54 | `SparseHistogram32`, `CumulativeROHistogram32`) that uses 32-bit counters. |
| 55 | |
| 56 | ## Counter Width |
| 57 | |
| 58 | All four histogram types ship in two flavors: |
| 59 | |
| 60 | - **u64-counter family** (`Histogram`, `AtomicHistogram`, `SparseHistogram`, `CumulativeROHistogram`): the default. Counts up to 2^64 − 1 per bucket. |
| 61 | - **u32-counter siblings** (`Histogram32`, `AtomicHistogram32`, `SparseHistogram32`, `CumulativeROHistogram32`): half the memory and serialization size, counts up to 2^32 − 1 per bucket. |
| 62 | |
| 63 | Pick the family based on the memory/range tradeoff. Conversions: |
| 64 | |
| 65 | - **Widening** (`u32` → `u64`) is infallible (`From`). |
| 66 | - **Narrowing** (`u64` → `u32`) is fallible (`TryFrom`, returns `Err(Overflow)`). Direct cross-variant + narrowing paths support the snapshot pipeline. |
| 67 | |
| 68 | ## Recommended Pipeline |
| 69 | |
| 70 | Pick the histogram type based on the *role* it plays in your data flow: |
| 71 | |
| 72 | - **Recording — `AtomicHistogram` (or `Histogram`).** Use the u64-counter types for the long-running, continuously-updated histogram. Counts here are unbounded over the lifetime of the process; `u64` heads off any practical risk of overflow. |
| 73 | - **Snapshot delta — `Histogram`, then narrowed.** When you take periodic snapshots and compute a delta with `checked_sub`, the delta covers only the activity in one window. Use `Histogram::checked_sub` to compute the delta, then `TryFrom` to narrow into a `*32` type. |
| 74 | - **Read-only analytics — `CumulativeROHistogram32`.** This is the recommended storage and query format for completed snapshots. The cumulative-prefix-sum representation gives you O(log n) quantile queries via binary search, while `u32` counts halve the on-the-wire and on-disk size versus `u64`. Narrowing is checked once against the *total count* (cheaper than per-bucket), and any total ≤ ~4.3B fits. |
| 75 | |
| 76 | ```rust |
| 77 | use histogram::{AtomicHistogram, CumulativeROHistogram32, Histogram}; |
| 78 | |
| 79 | let recorder = AtomicHistogram::new(7, 64).unwrap(); |
| 80 | # let snap_t0 = recorder.load(); |
| 81 | let snap_t1 = recorder.load(); |
| 82 | let delta = snap_t1.checked_sub(&snap_t0).unwrap(); |
| 83 | let analytic: CumulativeROHistogram32 = |
| 84 | CumulativeROHistogram32::try_from(&delta).unwrap(); |
| 85 | ``` |
| 86 | |
| 87 | If you don't take snapshots — i.e., you query the recording histogram directly — just stay on the u64 types everywhere. The narrowing optimization is specifically for the snapshot/delta pattern. |
| 88 | |
| 89 | For JavaScript-frontend plotting specifically, prefer `CumulativeROHistogram32` over a hypothetical f32-backed alternative: `u32` is exact up to ~4.3B (vs f32 exact only to ~16M), and cumulative-monotonicity is structurally preserved (no rounding-induced plateau artifacts in ECDF rendering). |
| 90 | |
| 91 | ## Features |
| 92 | |
| 93 | - `serde` -- Enables `Serialize` and `Deserialize` for histogram types. |
| 94 | - `schemars` -- Enables JSON Schema generation (implies `serde`). |
| 95 | |
| 96 | ## Documentation |
| 97 | |
| 98 | - [API Documentation](https://docs.rs/histogram) |
| 99 | - [Crates.io](https://crates.io/crates/histogram) |
| 100 | - [Repository](https://github.com/iopsystems/histogram) |
| 101 | |
| 102 | ## License |
| 103 | |
| 104 | Licensed under either of Apache License, Version 2.0 or MIT license at your |
| 105 | option. |