metrics_benchmark/
main.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use getopts::Options;
use hdrhistogram::Histogram as HdrHistogram;
use log::{error, info};
use metrics::{
    counter, gauge, histogram, Counter, Gauge, Histogram, Key, KeyName, Metadata, Recorder,
    SetRecorderError, SharedString, Unit,
};
use metrics_util::registry::{AtomicStorage, Registry};
use portable_atomic::AtomicU64;
use quanta::{Clock, Instant as QuantaInstant};
use std::{
    env,
    ops::Sub,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    thread,
    time::{Duration, Instant},
};

const LOOP_SAMPLE: u64 = 1000;

pub struct Controller {
    registry: Arc<Registry<Key, AtomicStorage>>,
}

impl Controller {
    /// Takes a snapshot of the recorder.
    /// Performs the traditional "upkeep" of a recorder i.e. clearing histogram buckets, etc.
    pub fn upkeep(&self) {
        let handles = self.registry.get_histogram_handles();

        for (_, histo) in handles {
            histo.clear();
        }
    }
}

/// A simplistic recorder for benchmarking.
///
/// Simulates typical recorder implementations by utilizing `Registry`, clearing histogram buckets, etc.
pub struct BenchmarkingRecorder {
    registry: Arc<Registry<Key, AtomicStorage>>,
}

impl BenchmarkingRecorder {
    /// Creates a new `BenchmarkingRecorder`.
    pub fn new() -> BenchmarkingRecorder {
        BenchmarkingRecorder { registry: Arc::new(Registry::atomic()) }
    }

    /// Gets a `Controller` attached to this recorder.
    pub fn controller(&self) -> Controller {
        Controller { registry: self.registry.clone() }
    }

    /// Installs this recorder as the global recorder.
    pub fn install(self) -> Result<(), SetRecorderError<Self>> {
        metrics::set_global_recorder(self)
    }
}

impl Recorder for BenchmarkingRecorder {
    fn describe_counter(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}

    fn describe_gauge(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}

    fn describe_histogram(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}

    fn register_counter(&self, key: &Key, _metadata: &Metadata<'_>) -> Counter {
        self.registry.get_or_create_counter(key, |c| Counter::from_arc(c.clone()))
    }

    fn register_gauge(&self, key: &Key, _metadata: &Metadata<'_>) -> Gauge {
        self.registry.get_or_create_gauge(key, |g| Gauge::from_arc(g.clone()))
    }

    fn register_histogram(&self, key: &Key, _metadata: &Metadata<'_>) -> Histogram {
        self.registry.get_or_create_histogram(key, |h| Histogram::from_arc(h.clone()))
    }
}

impl Default for BenchmarkingRecorder {
    fn default() -> Self {
        BenchmarkingRecorder::new()
    }
}

struct Generator {
    t0: Option<QuantaInstant>,
    gauge: i64,
    hist: HdrHistogram<u64>,
    done: Arc<AtomicBool>,
    rate_counter: Arc<AtomicU64>,
}

impl Generator {
    fn new(done: Arc<AtomicBool>, rate_counter: Arc<AtomicU64>) -> Generator {
        Generator {
            t0: None,
            gauge: 0,
            hist: HdrHistogram::<u64>::new_with_bounds(1, u64::max_value(), 3).unwrap(),
            done,
            rate_counter,
        }
    }

    fn run_slow(&mut self) {
        let clock = Clock::new();
        let mut loop_counter = 0;

        loop {
            loop_counter += 1;

            self.gauge += 1;

            let t1 = clock.recent();

            if let Some(t0) = self.t0 {
                let start = if loop_counter % LOOP_SAMPLE == 0 { Some(clock.now()) } else { None };

                counter!("ok").increment(1);
                gauge!("total").set(self.gauge as f64);
                histogram!("ok").record(t1.sub(t0));

                if let Some(val) = start {
                    let delta = clock.now() - val;
                    self.hist.saturating_record(delta.as_nanos() as u64);

                    // We also increment our global counter for the sample rate here.
                    self.rate_counter.fetch_add(LOOP_SAMPLE * 3, Ordering::AcqRel);

                    if self.done.load(Ordering::Relaxed) {
                        break;
                    }
                }
            }

            self.t0 = Some(t1);
        }
    }

    fn run_fast(&mut self) {
        let clock = Clock::new();
        let mut loop_counter = 0;

        let counter = counter!("ok");
        let gauge = gauge!("total");
        let histogram = histogram!("ok");

        loop {
            loop_counter += 1;

            self.gauge += 1;

            let t1 = clock.recent();

            if let Some(t0) = self.t0 {
                let start = if loop_counter % LOOP_SAMPLE == 0 { Some(clock.now()) } else { None };

                counter.increment(1);
                gauge.set(self.gauge as f64);
                histogram.record(t1.sub(t0));

                if let Some(val) = start {
                    let delta = clock.now() - val;
                    self.hist.saturating_record(delta.as_nanos() as u64);

                    // We also increment our global counter for the sample rate here.
                    self.rate_counter.fetch_add(LOOP_SAMPLE * 3, Ordering::AcqRel);

                    if self.done.load(Ordering::Relaxed) {
                        break;
                    }
                }
            }

            self.t0 = Some(t1);
        }
    }
}

impl Drop for Generator {
    fn drop(&mut self) {
        info!(
            "    sender latency: min: {:8} p50: {:8} p95: {:8} p99: {:8} p999: {:8} max: {:8}",
            nanos_to_readable(self.hist.min()),
            nanos_to_readable(self.hist.value_at_percentile(50.0)),
            nanos_to_readable(self.hist.value_at_percentile(95.0)),
            nanos_to_readable(self.hist.value_at_percentile(99.0)),
            nanos_to_readable(self.hist.value_at_percentile(99.9)),
            nanos_to_readable(self.hist.max())
        );
    }
}

fn print_usage(program: &str, opts: &Options) {
    let brief = format!("Usage: {} [options]", program);
    print!("{}", opts.usage(&brief));
}

pub fn opts() -> Options {
    let mut opts = Options::new();

    opts.optopt("d", "duration", "number of seconds to run the benchmark", "INTEGER");
    opts.optopt(
        "m",
        "mode",
        "whether or run the benchmark in slow or fast mode (static vs dynamic handles)",
        "STRING",
    );
    opts.optopt("p", "producers", "number of producers", "INTEGER");
    opts.optflag("h", "help", "print this help menu");

    opts
}

fn main() {
    pretty_env_logger::init();

    let args: Vec<String> = env::args().collect();
    let program = &args[0];
    let opts = opts();

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            error!("Failed to parse command line args: {}", f);
            return;
        }
    };

    if matches.opt_present("help") {
        print_usage(program, &opts);
        return;
    }

    info!("metrics benchmark");

    // Build our sink and configure the facets.
    let seconds = matches.opt_str("duration").unwrap_or_else(|| "60".to_owned()).parse().unwrap();
    let producers = matches.opt_str("producers").unwrap_or_else(|| "1".to_owned()).parse().unwrap();
    let mode = matches
        .opt_str("mode")
        .map(|s| if s.to_ascii_lowercase() == "fast" { "fast" } else { "slow" })
        .unwrap_or_else(|| "slow")
        .to_owned();

    info!("duration: {}s", seconds);
    info!("producers: {}", producers);

    let recorder = BenchmarkingRecorder::new();
    let controller = recorder.controller();
    recorder.install().expect("failed to install recorder");

    info!("sink configured");

    // Spin up our sample producers.
    let done = Arc::new(AtomicBool::new(false));
    let rate_counter = Arc::new(AtomicU64::new(0));
    let mut handles = Vec::new();

    for _ in 0..producers {
        let d = done.clone();
        let r = rate_counter.clone();
        let mode = mode.clone();
        let handle = thread::spawn(move || {
            let mut gen = Generator::new(d, r);
            if mode == "fast" {
                gen.run_fast();
            } else {
                gen.run_slow();
            }
        });

        handles.push(handle);
    }

    thread::spawn(|| loop {
        thread::sleep(Duration::from_millis(10));
        quanta::set_recent(quanta::Instant::now());
    });

    // Poll the controller to figure out the sample rate.
    let mut total = 0;
    let mut t0 = Instant::now();

    let mut upkeep_hist = HdrHistogram::<u64>::new_with_bounds(1, u64::max_value(), 3).unwrap();
    for _ in 0..seconds {
        let t1 = Instant::now();

        let start = Instant::now();
        controller.upkeep();
        let end = Instant::now();
        upkeep_hist.saturating_record(duration_as_nanos(end - start) as u64);

        let turn_total = rate_counter.load(Ordering::Acquire);
        let turn_delta = turn_total - total;
        total = turn_total;
        let rate = turn_delta as f64 / (duration_as_nanos(t1 - t0) / 1_000_000_000.0);

        info!("sample ingest rate: {:.0} samples/sec", rate);
        t0 = t1;
        thread::sleep(Duration::new(1, 0));
    }

    info!("--------------------------------------------------------------------------------");
    info!(" ingested samples total: {}", total);
    info!(
        "   recorder upkeep: min: {:8} p50: {:8} p95: {:8} p99: {:8} p999: {:8} max: {:8}",
        nanos_to_readable(upkeep_hist.min()),
        nanos_to_readable(upkeep_hist.value_at_percentile(50.0)),
        nanos_to_readable(upkeep_hist.value_at_percentile(95.0)),
        nanos_to_readable(upkeep_hist.value_at_percentile(99.0)),
        nanos_to_readable(upkeep_hist.value_at_percentile(99.9)),
        nanos_to_readable(upkeep_hist.max())
    );

    // Wait for the producers to finish so we can get their stats too.
    done.store(true, Ordering::SeqCst);
    for handle in handles {
        let _ = handle.join();
    }
}

fn duration_as_nanos(d: Duration) -> f64 {
    (d.as_secs() as f64 * 1e9) + d.subsec_nanos() as f64
}

fn nanos_to_readable(t: u64) -> String {
    let f = t as f64;
    if f < 1_000.0 {
        format!("{}ns", f)
    } else if f < 1_000_000.0 {
        format!("{:.0}μs", f / 1_000.0)
    } else if f < 2_000_000_000.0 {
        format!("{:.2}ms", f / 1_000_000.0)
    } else {
        format!("{:.3}s", f / 1_000_000_000.0)
    }
}