Skip to content

Commit ffaac12

Browse files
committed
feat(metrics/histogram): count() and sum() accessors
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 <[email protected]>
1 parent 12923ca commit ffaac12

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

src/metrics/histogram.rs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,16 @@ impl Histogram {
7676
self.observe_and_bucket(v);
7777
}
7878

79+
/// Returns the current sum of all observations.
80+
pub fn sum(&self) -> f64 {
81+
self.inner.read().sum
82+
}
83+
84+
/// Returns the current number of observations.
85+
pub fn count(&self) -> u64 {
86+
self.inner.read().count
87+
}
88+
7989
/// Observes the given value, returning the index of the first bucket the
8090
/// value is added to.
8191
///
@@ -166,4 +176,53 @@ mod tests {
166176
linear_buckets(0.0, 1.0, 10).collect::<Vec<_>>()
167177
);
168178
}
179+
180+
/// Checks that [`Histogram::count()`] works properly.
181+
#[test]
182+
fn count() {
183+
let histogram = Histogram::new([1.0_f64, 2.0, 3.0, 4.0, 5.0].into_iter());
184+
assert_eq!(
185+
histogram.count(),
186+
0,
187+
"histogram has zero observations when instantiated"
188+
);
189+
190+
histogram.observe(1.0);
191+
assert_eq!(histogram.count(), 1, "histogram has one observation");
192+
193+
histogram.observe(2.5);
194+
assert_eq!(histogram.count(), 2, "histogram has two observations");
195+
196+
histogram.observe(6.0);
197+
assert_eq!(histogram.count(), 3, "histogram has three observations");
198+
}
199+
200+
/// Checks that [`Histogram::sum()`] works properly.
201+
#[test]
202+
fn sum() {
203+
const BUCKETS: [f64; 3] = [10.0, 100.0, 1000.0];
204+
let histogram = Histogram::new(BUCKETS.into_iter());
205+
assert_eq!(
206+
histogram.sum(),
207+
0.0,
208+
"histogram sum is zero when instantiated"
209+
);
210+
211+
histogram.observe(3.0); // 3 + 4 + 15 + 101 = 123
212+
histogram.observe(4.0);
213+
histogram.observe(15.0);
214+
histogram.observe(101.0);
215+
assert_eq!(
216+
histogram.sum(),
217+
123.0,
218+
"histogram sum records accurate sum of observations"
219+
);
220+
221+
histogram.observe(1111.0);
222+
assert_eq!(
223+
histogram.sum(),
224+
1234.0,
225+
"histogram sum records accurate sum of observations"
226+
);
227+
}
169228
}

0 commit comments

Comments
 (0)