Skip to content
Myr

unix_timer.rs

This file

Path

src/timer/unix_timer.rs

89 lines · 2.5 KiB · Rust

Last changed by

Merge pull request #790 from sharkdp/new-metricsDavid Peterbefore adoptionf26c015

History of this file

Take it

1#![cfg(not(windows))]23use std::io;4use std::mem::MaybeUninit;5use std::os::unix::process::ExitStatusExt;6use std::process::{Child, ExitStatus};78use anyhow::Result;910use crate::quantity::{byte, kibibyte, microsecond, second, Information, Time};1112#[derive(Debug, Copy, Clone)]13struct ResourceUsage {14    /// Total amount of time spent executing in user mode15    pub time_user: Time,1617    /// Total amount of time spent executing in kernel mode18    pub time_system: Time,1920    /// Maximum amount of memory used by the process, in bytes21    pub memory_usage: Information,22}2324#[allow(clippy::useless_conversion)]25fn convert_timeval(tv: libc::timeval) -> Time {26    let sec = tv.tv_sec as f64;27    let usec = tv.tv_usec as f64;2829    Time::new::<second>(sec) + Time::new::<microsecond>(usec)30}3132#[allow(clippy::useless_conversion)]33fn wait4(mut child: Child) -> io::Result<(ExitStatus, ResourceUsage)> {34    drop(child.stdin.take());3536    let pid = child.id() as i32;37    let mut status = 0;38    let mut rusage = MaybeUninit::zeroed();3940    loop {41        let result = unsafe { libc::wait4(pid, &mut status, 0, rusage.as_mut_ptr()) };42        if result >= 0 {43            break;44        }45        let error = io::Error::last_os_error();46        if error.kind() != io::ErrorKind::Interrupted {47            return Err(error);48        }49    }5051    let rusage = unsafe { rusage.assume_init() };5253    let memory_usage_byte = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {54        // Linux and *BSD return the value in KibiBytes, Darwin flavors in bytes55        // A f64 can represent integers up to 2^53 exactly, so we can represent56        // all values up to 2^53 bytes = 8 PiB exactly. Beyond that, our precision57        // is larger than 1 byte, but that's considered acceptable.58        Information::new::<byte>(rusage.ru_maxrss as f64)59    } else {60        Information::new::<kibibyte>(rusage.ru_maxrss as f64)61    };6263    Ok((64        ExitStatus::from_raw(status),65        ResourceUsage {66            time_user: convert_timeval(rusage.ru_utime),67            time_system: convert_timeval(rusage.ru_stime),68            memory_usage: memory_usage_byte.into(),69        },70    ))71}7273pub struct CPUTimer {}7475impl CPUTimer {76    pub fn start() -> Self {77        Self {}78    }7980    pub fn stop(&self, child: Child) -> Result<(Time, Time, Option<Information>, ExitStatus)> {81        let (status, usage) = wait4(child)?;82        Ok((83            usage.time_user,84            usage.time_system,85            Some(usage.memory_usage),86            status,87        ))88    }89}