Skip to content
Myr

macos_counters.rs

This file

Path

src/timer/macos_counters.rs

55 lines · 1.9 KiB · Rust

Last changed by

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

History of this file

Take it

1use std::io;2use std::mem::MaybeUninit;3use std::process::Child;45use crate::benchmark::measurement::HardwareCounters;67/// Wait for exit without reaping: proc_pid_rusage can still inspect the zombie,8/// and the existing wait4 call can subsequently collect CPU times and peak RSS.9pub fn wait(child: &mut Child) -> io::Result<()> {10    drop(child.stdin.take());11    let mut info = MaybeUninit::uninit();12    loop {13        // SAFETY: info points to writable siginfo_t storage. WNOWAIT preserves the child.14        let result = unsafe {15            libc::waitid(16                libc::P_PID,17                child.id(),18                info.as_mut_ptr(),19                libc::WEXITED | libc::WNOWAIT,20            )21        };22        if result == 0 {23            return Ok(());24        }25        let error = io::Error::last_os_error();26        if error.kind() != io::ErrorKind::Interrupted {27            return Err(error);28        }29    }30}3132pub fn read(pid: u32) -> HardwareCounters {33    let mut usage = MaybeUninit::<libc::rusage_info_v4>::zeroed();34    // SAFETY: the buffer has the layout and size requested by RUSAGE_INFO_V4.35    // Despite the pointer-to-pointer signature, this API writes directly into the buffer.36    let result = unsafe {37        libc::proc_pid_rusage(38            pid as libc::pid_t,39            libc::RUSAGE_INFO_V4,40            usage.as_mut_ptr().cast(),41        )42    };43    if result != 0 {44        return HardwareCounters::default();45    }46    // SAFETY: the call succeeded and initialized the buffer.47    let usage = unsafe { usage.assume_init() };48    HardwareCounters {49        // Like macOS time(1), omit zero counters: the API can succeed on systems50        // where instruction/cycle accounting is unavailable.51        cpu_cycles: (usage.ri_cycles != 0).then_some(usage.ri_cycles),52        instructions: (usage.ri_instructions != 0).then_some(usage.ri_instructions),53        ..Default::default()54    }55}