Skip to content

Commit

Permalink
feat(metrics/histogram): count() and sum() accessors
Browse files Browse the repository at this point in the history
fixes prometheus#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 <me+cratelyn@katelyn.world>
  • Loading branch information
cratelyn committed Nov 18, 2024
1 parent 12923ca commit ffaac12
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/metrics/histogram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ impl Histogram {
self.observe_and_bucket(v);
}

/// Returns the current sum of all observations.
pub fn sum(&self) -> f64 {
self.inner.read().sum
}

/// Returns the current number of observations.
pub fn count(&self) -> u64 {
self.inner.read().count
}

/// Observes the given value, returning the index of the first bucket the
/// value is added to.
///
Expand Down Expand Up @@ -166,4 +176,53 @@ mod tests {
linear_buckets(0.0, 1.0, 10).collect::<Vec<_>>()
);
}

/// Checks that [`Histogram::count()`] works properly.
#[test]
fn count() {
let histogram = Histogram::new([1.0_f64, 2.0, 3.0, 4.0, 5.0].into_iter());
assert_eq!(
histogram.count(),
0,
"histogram has zero observations when instantiated"
);

histogram.observe(1.0);
assert_eq!(histogram.count(), 1, "histogram has one observation");

histogram.observe(2.5);
assert_eq!(histogram.count(), 2, "histogram has two observations");

histogram.observe(6.0);
assert_eq!(histogram.count(), 3, "histogram has three observations");
}

/// Checks that [`Histogram::sum()`] works properly.
#[test]
fn sum() {
const BUCKETS: [f64; 3] = [10.0, 100.0, 1000.0];
let histogram = Histogram::new(BUCKETS.into_iter());
assert_eq!(
histogram.sum(),
0.0,
"histogram sum is zero when instantiated"
);

histogram.observe(3.0); // 3 + 4 + 15 + 101 = 123
histogram.observe(4.0);
histogram.observe(15.0);
histogram.observe(101.0);
assert_eq!(
histogram.sum(),
123.0,
"histogram sum records accurate sum of observations"
);

histogram.observe(1111.0);
assert_eq!(
histogram.sum(),
1234.0,
"histogram sum records accurate sum of observations"
);
}
}

0 comments on commit ffaac12

Please sign in to comment.