Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(metrics/histogram): 🍪 count() and sum() accessors #242

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"
);
}
}