mod.rs
This file
Path
src/timer/mod.rs
103 lines · 2.5 KiB · Rust
Last changed by
Merge pull request #965 from sharkdp/codex/wait4-resource-usageDavid Peterbefore adoptione43bf85
History of this fileTake 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::fd::AsFd;1516#[cfg(target_os = "windows")]17use windows_sys::Win32::System::Threading::CREATE_SUSPENDED;1819use crate::benchmark::measurement::Measurement;20use wall_clock_timer::WallClockTimer;2122use std::io::Read;23use std::process::{ChildStdout, Command};2425use anyhow::Result;2627/// Discard the output of a child process.28fn discard(output: ChildStdout) {29 const CHUNK_SIZE: usize = 64 << 10;3031 #[cfg(target_os = "linux")]32 {33 if let Ok(file) = File::create("/dev/null") {34 while let Ok(bytes) = splice(35 output.as_fd(),36 None,37 file.as_fd(),38 None,39 CHUNK_SIZE,40 SpliceFFlags::empty(),41 ) {42 if bytes == 0 {43 break;44 }45 }46 }47 }4849 let mut output = output;50 let mut buf = [0; CHUNK_SIZE];51 while let Ok(bytes) = output.read(&mut buf) {52 if bytes == 0 {53 break;54 }55 }56}5758/// Execute the given command and return a timing summary59pub fn execute_and_measure(mut command: Command) -> Result<Measurement> {60 #[cfg(not(windows))]61 let cpu_timer = self::unix_timer::CPUTimer::start();6263 #[cfg(windows)]64 {65 use std::os::windows::process::CommandExt;6667 // Create the process in a suspended state so that we don't miss any cpu time between process creation and `CPUTimer` start.68 command.creation_flags(CREATE_SUSPENDED);69 }7071 let wallclock_timer = WallClockTimer::start();72 let mut child = command.spawn()?;7374 #[cfg(windows)]75 let cpu_timer = {76 // SAFETY: We created a suspended process77 unsafe { self::windows_timer::CPUTimer::start_suspended_process(&child) }78 };7980 if let Some(output) = child.stdout.take() {81 // Handle CommandOutputPolicy::Pipe82 discard(output);83 }8485 #[cfg(not(windows))]86 let (time_user, time_system, peak_memory_usage, exit_status) = cpu_timer.stop(child)?;8788 #[cfg(windows)]89 let exit_status = child.wait()?;9091 let time_wall_clock = wallclock_timer.stop();9293 #[cfg(windows)]94 let (time_user, time_system, peak_memory_usage) = cpu_timer.stop();9596 Ok(Measurement {97 time_wall_clock,98 time_user,99 time_system,100 peak_memory_usage,101 exit_status,102 })103}