mod.rs
This file
Path
src/timer/mod.rs
114 lines · 2.6 KiB · Rust
Last changed by
Fix user and kernel times on WindowsClemens Wasserbefore adoptionac8c114
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::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#[cfg(not(windows))]25#[derive(Debug, Copy, Clone)]26struct CPUTimes {27 /// Total amount of time spent executing in user mode28 pub user_usec: i64,2930 /// Total amount of time spent executing in kernel mode31 pub system_usec: i64,32}3334/// Used to indicate the result of running a command35#[derive(Debug, Copy, Clone)]36pub struct TimerResult {37 pub time_real: Second,38 pub time_user: Second,39 pub time_system: Second,4041 /// The exit status of the process42 pub status: ExitStatus,43}4445/// Discard the output of a child process.46fn discard(output: ChildStdout) {47 const CHUNK_SIZE: usize = 64 << 10;4849 #[cfg(target_os = "linux")]50 {51 if let Ok(file) = File::create("/dev/null") {52 while let Ok(bytes) = splice(53 output.as_raw_fd(),54 None,55 file.as_raw_fd(),56 None,57 CHUNK_SIZE,58 SpliceFFlags::empty(),59 ) {60 if bytes == 0 {61 break;62 }63 }64 }65 }6667 let mut output = output;68 let mut buf = [0; CHUNK_SIZE];69 while let Ok(bytes) = output.read(&mut buf) {70 if bytes == 0 {71 break;72 }73 }74}7576/// Execute the given command and return a timing summary77pub fn execute_and_measure(mut command: Command) -> Result<TimerResult> {78 #[cfg(not(windows))]79 let cpu_timer = self::unix_timer::CPUTimer::start();8081 #[cfg(windows)]82 {83 use std::os::windows::process::CommandExt;8485 // Create a suspended process86 command.creation_flags(4);87 }8889 let wallclock_timer = WallClockTimer::start();90 let mut child = command.spawn()?;9192 #[cfg(windows)]93 let cpu_timer = {94 // SAFETY: We created a suspended process95 unsafe { self::windows_timer::CPUTimer::start_suspended_process(&child) }96 };9798 if let Some(output) = child.stdout.take() {99 // Handle CommandOutputPolicy::Pipe100 discard(output);101 }102103 let status = child.wait()?;104105 let time_real = wallclock_timer.stop();106 let (time_user, time_system) = cpu_timer.stop();107108 Ok(TimerResult {109 time_real,110 time_user,111 time_system,112 status,113 })114}