|
| 1 | +// Benchmark inspired by |
| 2 | +// https://github.com/tikv/rust-prometheus/blob/ab1ca7285d3463504381a5025ae1951e020d6796/benches/text_encoder.rs:write |
| 3 | + |
| 4 | +use criterion::{black_box, criterion_group, criterion_main, Criterion}; |
| 5 | +use prometheus_client::encoding::proto::{encode, EncodeMetric}; |
| 6 | +use prometheus_client::encoding::Encode; |
| 7 | +use prometheus_client::metrics::counter::Counter; |
| 8 | +use prometheus_client::metrics::family::Family; |
| 9 | +use prometheus_client::metrics::histogram::{exponential_buckets, Histogram}; |
| 10 | +use prometheus_client::registry::Registry; |
| 11 | +use std::fmt::{Display, Formatter}; |
| 12 | + |
| 13 | +pub fn proto(c: &mut Criterion) { |
| 14 | + c.bench_function("encode", |b| { |
| 15 | + #[derive(Clone, Hash, PartialEq, Eq, Encode)] |
| 16 | + struct Labels { |
| 17 | + path: String, |
| 18 | + method: Method, |
| 19 | + some_number: u64, |
| 20 | + } |
| 21 | + |
| 22 | + #[derive(Clone, Hash, PartialEq, Eq, Encode)] |
| 23 | + enum Method { |
| 24 | + Get, |
| 25 | + #[allow(dead_code)] |
| 26 | + Put, |
| 27 | + } |
| 28 | + |
| 29 | + impl Display for Method { |
| 30 | + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 31 | + match self { |
| 32 | + Method::Get => write!(f, "Get"), |
| 33 | + Method::Put => write!(f, "Put"), |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + #[derive(Clone, Hash, PartialEq, Eq, Encode)] |
| 39 | + enum Region { |
| 40 | + Africa, |
| 41 | + #[allow(dead_code)] |
| 42 | + Asia, |
| 43 | + } |
| 44 | + |
| 45 | + let mut registry = Registry::<Box<dyn EncodeMetric>>::default(); |
| 46 | + |
| 47 | + for i in 0..100 { |
| 48 | + let counter_family = Family::<Labels, Counter>::default(); |
| 49 | + let histogram_family = Family::<Region, Histogram>::new_with_constructor(|| { |
| 50 | + Histogram::new(exponential_buckets(1.0, 2.0, 10)) |
| 51 | + }); |
| 52 | + |
| 53 | + registry.register( |
| 54 | + format!("my_counter{}", i), |
| 55 | + "My counter", |
| 56 | + Box::new(counter_family.clone()), |
| 57 | + ); |
| 58 | + registry.register( |
| 59 | + format!("my_histogram{}", i), |
| 60 | + "My histogram", |
| 61 | + Box::new(histogram_family.clone()), |
| 62 | + ); |
| 63 | + |
| 64 | + for j in 0_u32..100 { |
| 65 | + counter_family |
| 66 | + .get_or_create(&Labels { |
| 67 | + path: format!("/path/{}", i), |
| 68 | + method: Method::Get, |
| 69 | + some_number: j.into(), |
| 70 | + }) |
| 71 | + .inc(); |
| 72 | + |
| 73 | + histogram_family |
| 74 | + .get_or_create(&Region::Africa) |
| 75 | + .observe(j.into()); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + b.iter(|| { |
| 80 | + let metric_set = encode(®istry); |
| 81 | + black_box(metric_set); |
| 82 | + }) |
| 83 | + }); |
| 84 | +} |
| 85 | + |
| 86 | +criterion_group!(benches, proto); |
| 87 | +criterion_main!(benches); |
0 commit comments