Skip to content
Myr

linux_counters.rs

This file

Path

src/timer/linux_counters.rs

113 lines · 3.7 KiB · Rust

Last changed by

Support hardware counters (instructions, cache misses, ...) (#983)David Peterbefore adoptionbc3a3f0

History of this file

Take it

1use std::fs::File;2use std::io::Read;34use crate::benchmark::measurement::HardwareCounters;56/// Disabled events on the spawning thread, inherited and enabled by the child's exec.7/// The parent never enables its own events, so its work is not counted.8pub struct CounterGroup {9    events: [Option<File>; 5],10}1112impl CounterGroup {13    #[cfg(all(14        target_pointer_width = "64",15        any(16            target_arch = "aarch64",17            target_arch = "x86_64",18            target_arch = "riscv64",19            target_arch = "powerpc64",20            target_arch = "loongarch64"21        )22    ))]23    pub fn new() -> Self {24        use perf_event_open_sys::{bindings, perf_event_open};25        use std::os::fd::{AsRawFd, FromRawFd};2627        let mut group_leader = -1;28        let events = [29            bindings::PERF_COUNT_HW_CPU_CYCLES,30            bindings::PERF_COUNT_HW_INSTRUCTIONS,31            bindings::PERF_COUNT_HW_CACHE_REFERENCES,32            bindings::PERF_COUNT_HW_CACHE_MISSES,33            bindings::PERF_COUNT_HW_BRANCH_MISSES,34        ]35        .map(|config| {36            let mut attr = bindings::perf_event_attr {37                type_: bindings::PERF_TYPE_HARDWARE,38                size: std::mem::size_of::<bindings::perf_event_attr>() as u32,39                config: u64::from(config),40                ..Default::default()41            };42            // Don't start counting immediately.43            attr.set_disabled(1);44            // Start counting when the child executes the benchmark program.45            attr.set_enable_on_exec(1);46            // New child processes and threads inherit the counters.47            attr.set_inherit(1);48            // Exclude kernel execution.49            attr.set_exclude_kernel(1);50            // Exclude hypervisor execution.51            attr.set_exclude_hv(1);5253            // Attach counters to the calling thread.54            const CURRENT_THREAD: libc::pid_t = 0;55            // Count on whichever CPU the task runs on.56            const ANY_CPU: libc::c_int = -1;5758            // SAFETY: attr is initialized and sized for the kernel API.59            let fd = unsafe {60                perf_event_open(61                    &mut attr,62                    CURRENT_THREAD,63                    ANY_CPU,64                    group_leader,65                    bindings::PERF_FLAG_FD_CLOEXEC.into(),66                )67            };68            if fd < 0 {69                return None;70            }71            // SAFETY: perf_event_open returned a new, valid descriptor.72            let event = unsafe { File::from_raw_fd(fd) };73            if group_leader == -1 {74                group_leader = event.as_raw_fd();75            }76            Some(event)77        });78        Self { events }79    }8081    #[cfg(not(all(82        target_pointer_width = "64",83        any(84            target_arch = "aarch64",85            target_arch = "x86_64",86            target_arch = "riscv64",87            target_arch = "powerpc64",88            target_arch = "loongarch64"89        )90    )))]91    pub fn new() -> Self {92        Self {93            events: Default::default(),94        }95    }9697    /// Read raw counts after the child has exited. Like poop, do not scale for multiplexing.98    pub fn read(mut self) -> HardwareCounters {99        let [cpu_cycles, instructions, cache_references, cache_misses, branch_misses] =100            self.events.each_mut().map(|event| {101                let mut bytes = [0; 8];102                event.as_mut()?.read_exact(&mut bytes).ok()?;103                Some(u64::from_ne_bytes(bytes))104            });105        HardwareCounters {106            cpu_cycles,107            instructions,108            cache_references,109            cache_misses,110            branch_misses,111        }112    }113}