Skip to main content

mz_bench_util/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Criterion that counts instructions when `MZ_BENCH_MEASUREMENT=instructions`.
11//!
12//! Benches import from this crate instead of `criterion` and measure wall time
13//! by default, or the user-space instructions the benchmarking thread retires.
14//! Instruction counts miss other threads and the kernel, so benches that spawn
15//! threads or do I/O stay on plain criterion.
16
17use std::fs::File;
18use std::io::Read;
19use std::time::{Duration, Instant};
20
21use criterion::measurement::{ValueFormatter, WallTime};
22pub use criterion::*;
23
24pub type Criterion = criterion::Criterion<Measurement>;
25pub type Bencher<'a> = criterion::Bencher<'a, Measurement>;
26
27#[macro_export]
28macro_rules! criterion_group {
29    ($name:ident, $($target:path),+ $(,)?) => {
30        $crate::criterion::criterion_group! {
31            name = $name;
32            config = $crate::criterion::Criterion::default()
33                .with_measurement($crate::Measurement::from_env());
34            targets = $($target),+
35        }
36    };
37}
38
39#[doc(hidden)]
40pub use criterion;
41
42static WALL: WallTime = WallTime;
43
44/// Wall time, or with a counter, instruction counts passed off as nanoseconds
45/// so that criterion's wall-time arithmetic applies unchanged.
46pub struct Measurement(Option<File>);
47
48impl Measurement {
49    /// Reads `MZ_BENCH_MEASUREMENT`, panicking unless it is unset, `wall`, or
50    /// `instructions` on a host that can count them.
51    pub fn from_env() -> Self {
52        Measurement(match std::env::var("MZ_BENCH_MEASUREMENT").as_deref() {
53            Err(_) | Ok("wall") => None,
54            Ok("instructions") => Some(open_instruction_counter()),
55            Ok(other) => panic!("MZ_BENCH_MEASUREMENT must be wall or instructions, not {other}"),
56        })
57    }
58}
59
60impl criterion::measurement::Measurement for Measurement {
61    type Intermediate = (Instant, u64);
62    type Value = Duration;
63
64    fn start(&self) -> (Instant, u64) {
65        (Instant::now(), self.0.as_ref().map_or(0, read))
66    }
67
68    fn end(&self, (start, count): (Instant, u64)) -> Duration {
69        match &self.0 {
70            None => start.elapsed(),
71            Some(counter) => Duration::from_nanos(read(counter) - count),
72        }
73    }
74
75    fn add(&self, v1: &Duration, v2: &Duration) -> Duration {
76        *v1 + *v2
77    }
78
79    fn zero(&self) -> Duration {
80        Duration::ZERO
81    }
82
83    fn to_f64(&self, value: &Duration) -> f64 {
84        WALL.to_f64(value)
85    }
86
87    fn formatter(&self) -> &dyn ValueFormatter {
88        match self.0 {
89            None => WALL.formatter(),
90            Some(_) => &Instructions,
91        }
92    }
93}
94
95struct Instructions;
96
97impl ValueFormatter for Instructions {
98    fn scale_values(&self, _: f64, _: &mut [f64]) -> &'static str {
99        "instructions"
100    }
101
102    fn scale_throughputs(&self, _: f64, _: &Throughput, _: &mut [f64]) -> &'static str {
103        "instructions"
104    }
105
106    fn scale_for_machines(&self, _: &mut [f64]) -> &'static str {
107        "instructions"
108    }
109}
110
111#[cfg(target_os = "linux")]
112fn open_instruction_counter() -> File {
113    use std::os::fd::FromRawFd;
114
115    // `struct perf_event_attr`, which libc lacks: `type` (0, PERF_TYPE_HARDWARE)
116    // and `size` in the first word, `config` in the second, flags in the sixth.
117    let mut attr = [0u64; 16];
118    attr[0] = 128 << 32;
119    attr[1] = 1; // PERF_COUNT_HW_INSTRUCTIONS
120    attr[5] = (1 << 5) | (1 << 6); // exclude_kernel, exclude_hv
121    // SAFETY: `attr` is a `perf_event_attr` of the size it declares. pid 0 and
122    // cpu -1 count the calling thread on any CPU.
123    let fd = unsafe { libc::syscall(libc::SYS_perf_event_open, attr.as_ptr(), 0, -1, -1, 0) };
124    assert!(
125        fd >= 0,
126        "perf_event_open: {}. It needs kernel.perf_event_paranoid <= 2, and CAP_PERFMON in Docker.",
127        std::io::Error::last_os_error()
128    );
129    // SAFETY: the kernel just returned `fd`, and nothing else owns it.
130    unsafe { File::from_raw_fd(i32::try_from(fd).unwrap()) }
131}
132
133#[cfg(not(target_os = "linux"))]
134fn open_instruction_counter() -> File {
135    panic!("counting instructions needs Linux perf events")
136}
137
138fn read(mut counter: &File) -> u64 {
139    let mut buf = [0; 8];
140    counter.read_exact(&mut buf).expect("reading the counter");
141    u64::from_ne_bytes(buf)
142}