-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics_collection.rs
56 lines (45 loc) · 1.47 KB
/
metrics_collection.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use orx_concurrent_vec::*;
use std::time::Duration;
#[derive(Debug, Default)]
struct Metric {
sum: i32,
count: i32,
}
impl Metric {
fn aggregate(self, value: &i32) -> Self {
Self {
sum: self.sum + value,
count: self.count + 1,
}
}
}
fn main() {
// record measurements in random intervals, roughly every 2ms
let measurements = ConcurrentVec::new();
// collect metrics every 100 milliseconds
let metrics = ConcurrentVec::new();
std::thread::scope(|s| {
// thread to store measurements as they arrive
s.spawn(|| {
for i in 0..100 {
std::thread::sleep(Duration::from_millis(i % 5));
// collect measurements and push to measurements vec
measurements.push(i as i32);
}
});
// thread to collect metrics every 100 milliseconds
s.spawn(|| {
for _ in 0..10 {
// safely read from measurements vec to compute the metric at that instant
let metric = measurements.fold(Metric::default(), |x, value| x.aggregate(value));
// push result to metrics
metrics.push(metric);
std::thread::sleep(Duration::from_millis(100));
}
});
});
let measurements: Vec<_> = measurements.to_vec();
let averages: Vec<_> = metrics.to_vec();
assert_eq!(measurements.len(), 100);
assert_eq!(averages.len(), 10);
}