Skip to content
Myr

mod.rs

This file

Path

src/timer/mod.rs

103 lines · 2.4 KiB · Rust

Last changed by

Address review commentsTavian Barnesbefore adoption3df63ba

History of this file

Take it

1mod wall_clock_timer;23#[cfg(windows)]4mod windows_timer;56#[cfg(not(windows))]7mod unix_timer;89#[cfg(target_os = "linux")]10use nix::fcntl::{splice, SpliceFFlags};11#[cfg(target_os = "linux")]12use std::fs::File;13#[cfg(target_os = "linux")]14use std::os::unix::io::AsRawFd;1516use crate::util::units::Second;17use wall_clock_timer::WallClockTimer;1819use std::io::Read;20use std::process::{ChildStdout, Command, ExitStatus};2122use anyhow::Result;2324#[derive(Debug, Copy, Clone)]25struct CPUTimes {26    /// Total amount of time spent executing in user mode27    pub user_usec: i64,2829    /// Total amount of time spent executing in kernel mode30    pub system_usec: i64,31}3233/// Used to indicate the result of running a command34#[derive(Debug, Copy, Clone)]35pub struct TimerResult {36    pub time_real: Second,37    pub time_user: Second,38    pub time_system: Second,3940    /// The exit status of the process41    pub status: ExitStatus,42}4344/// Discard the output of a child process.45fn discard(output: ChildStdout) {46    const CHUNK_SIZE: usize = 64 << 10;4748    #[cfg(target_os = "linux")]49    {50        if let Ok(file) = File::create("/dev/null") {51            while let Ok(bytes) = splice(52                output.as_raw_fd(),53                None,54                file.as_raw_fd(),55                None,56                CHUNK_SIZE,57                SpliceFFlags::empty(),58            ) {59                if bytes == 0 {60                    break;61                }62            }63        }64    }6566    let mut output = output;67    let mut buf = [0; CHUNK_SIZE];68    while let Ok(bytes) = output.read(&mut buf) {69        if bytes == 0 {70            break;71        }72    }73}7475/// Execute the given command and return a timing summary76pub fn execute_and_measure(mut command: Command) -> Result<TimerResult> {77    let wallclock_timer = WallClockTimer::start();7879    #[cfg(not(windows))]80    let cpu_timer = self::unix_timer::CPUTimer::start();8182    let mut child = command.spawn()?;8384    #[cfg(windows)]85    let cpu_timer = self::windows_timer::CPUTimer::start_for_process(&child);8687    if let Some(output) = child.stdout.take() {88        // Handle CommandOutputPolicy::Pipe89        discard(output);90    }9192    let status = child.wait()?;9394    let (time_user, time_system) = cpu_timer.stop();95    let time_real = wallclock_timer.stop();9697    Ok(TimerResult {98        time_real,99        time_user,100        time_system,101        status,102    })103}