Skip to content

Commit 09580aa

Browse files
committed
feat(metrics/histogram): count() and sum() accessors
fixes #241. this commit introduces two new public methods to `Histogram`; `sum()` and `count()` return the sum of all observations and the number of observations made, respectively. Signed-off-by: katelyn martin <[email protected]>
1 parent ec3a549 commit 09580aa

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/metrics/histogram.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,18 @@ impl Histogram {
8181
self.observe_and_bucket(v);
8282
}
8383

84+
/// Returns the current sum of all observations.
85+
#[cfg(any(test, feature = "test-util"))]
86+
pub fn sum(&self) -> f64 {
87+
self.inner.read().sum
88+
}
89+
90+
/// Returns the current number of observations.
91+
#[cfg(any(test, feature = "test-util"))]
92+
pub fn count(&self) -> u64 {
93+
self.inner.read().count
94+
}
95+
8496
/// Observes the given value, returning the index of the first bucket the
8597
/// value is added to.
8698
///
@@ -212,4 +224,53 @@ mod tests {
212224
let res = exponential_buckets_range(0.0, 32.0, 6).collect::<Vec<_>>();
213225
assert!(res.is_empty());
214226
}
227+
228+
/// Checks that [`Histogram::count()`] works properly.
229+
#[test]
230+
fn count() {
231+
let histogram = Histogram::new([1.0_f64, 2.0, 3.0, 4.0, 5.0]);
232+
assert_eq!(
233+
histogram.count(),
234+
0,
235+
"histogram has zero observations when instantiated"
236+
);
237+
238+
histogram.observe(1.0);
239+
assert_eq!(histogram.count(), 1, "histogram has one observation");
240+
241+
histogram.observe(2.5);
242+
assert_eq!(histogram.count(), 2, "histogram has two observations");
243+
244+
histogram.observe(6.0);
245+
assert_eq!(histogram.count(), 3, "histogram has three observations");
246+
}
247+
248+
/// Checks that [`Histogram::sum()`] works properly.
249+
#[test]
250+
fn sum() {
251+
const BUCKETS: [f64; 3] = [10.0, 100.0, 1000.0];
252+
let histogram = Histogram::new(BUCKETS);
253+
assert_eq!(
254+
histogram.sum(),
255+
0.0,
256+
"histogram sum is zero when instantiated"
257+
);
258+
259+
histogram.observe(3.0); // 3 + 4 + 15 + 101 = 123
260+
histogram.observe(4.0);
261+
histogram.observe(15.0);
262+
histogram.observe(101.0);
263+
assert_eq!(
264+
histogram.sum(),
265+
123.0,
266+
"histogram sum records accurate sum of observations"
267+
);
268+
269+
histogram.observe(1111.0);
270+
assert_eq!(
271+
histogram.sum(),
272+
1234.0,
273+
"histogram sum records accurate sum of observations"
274+
);
275+
}
215276
}

0 commit comments

Comments
 (0)