base2histogram
base2histogram is a Rust histogram library for fast percentile estimation with
base-2 logarithmic bucketing.
It is designed for latency and metrics workloads where:
- recording should be
O(1), - memory usage should stay bounded,
- percentile queries should be cheap,
- and large
u64values should still be representable without resizing.
Features
- Fixed-size histogram over the full
u64range. - Base-2 logarithmic buckets with bounded relative error.
- Cheap percentile queries such as
P50,P99, andP99.9. - Optional multi-slot mode for sliding-window style aggregation.
- No external runtime or allocator tricks required.
Bucket Model
The default configuration uses 3 significant bits to define a bucket:
- values
0..=7are represented exactly, - values
8..=15are grouped with step size2, - values
16..=31are grouped with step size4, - larger values keep doubling the bucket width with the magnitude.
This keeps relative error bounded while covering the entire u64 range in a
small, fixed number of buckets.
Usage
use Histogram;
let mut hist = new;
hist.record;
hist.record;
hist.record;
hist.record_n;
assert_eq!;
let p50 = hist.percentile;
let p99 = hist.percentile;
assert!;
percentile() returns the minimum value of the bucket that contains the target
percentile. This is intentional: the histogram stores bucketed counts, not raw
samples.
Sliding Window
Use with_slots() plus advance() when metrics should be aggregated over a
bounded set of recent windows:
use Histogram;
let mut hist = with_slots;
hist.record_n;
hist.advance;
hist.record_n;
assert_eq!;
hist.advance;
// The oldest slot is evicted once the slot limit is reached.
assert_eq!;
Common Stats
use Histogram;
let mut hist = new;
hist.record_n;
hist.record_n;
let stats = hist.percentile_stats;
assert_eq!;
assert_eq!;
assert_eq!;
Development
Common local commands:
License
Licensed under Apache-2.0. See LICENSE.