shell.rs
This file
Path
src/shell.rs
87 lines · 2.1 KiB · Rust
Last changed by
Refactor timer moduleDavid Peterbefore adoptiondefafdf
History of this fileTake it
1use std::process::{ExitStatus, Stdio};23use crate::options::Shell;45use anyhow::{Context, Result};67/// Used to indicate the result of running a command8#[derive(Debug, Copy, Clone)]9pub struct ExecuteResult {10 /// The amount of user time the process used11 pub user_time: f64,1213 /// The amount of cpu time the process used14 pub system_time: f64,1516 /// The exit status of the process17 pub status: ExitStatus,18}1920fn randomized_environment_offset_value() -> String {21 "X".repeat(rand::random::<usize>() % 4096usize)22}2324/// Execute the given command and return a timing summary25#[cfg(not(windows))]26pub fn execute_and_time(27 stdout: Stdio,28 stderr: Stdio,29 command: &str,30 shell: &Shell,31) -> Result<ExecuteResult> {32 let cpu_timer = crate::timer::unix_timer::CPUTimer::start();3334 let status = shell35 .command()36 .arg("-c")37 .arg(command)38 .env(39 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",40 randomized_environment_offset_value(),41 )42 .stdin(Stdio::null())43 .stdout(stdout)44 .stderr(stderr)45 .status()46 .with_context(|| format!("Failed to run command '{}'", command))?;4748 let (user_time, system_time) = cpu_timer.stop();4950 Ok(ExecuteResult {51 user_time,52 system_time,53 status,54 })55}5657/// Execute the given command and return a timing summary58#[cfg(windows)]59pub fn execute_and_time(60 stdout: Stdio,61 stderr: Stdio,62 command: &str,63 shell: &Shell,64) -> Result<ExecuteResult> {65 let mut child = shell66 .command()67 .arg("/C")68 .arg(command)69 .env(70 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",71 randomized_environment_offset_value(),72 )73 .stdin(Stdio::null())74 .stdout(stdout)75 .stderr(stderr)76 .spawn()77 .with_context(|| format!("Failed to run command '{}'", command))?;78 let cpu_timer = crate::timer::windows_timer::CPUTimer::start_for_process(&child);79 let status = child.wait()?;8081 let (user_time, system_time) = cpu_timer.stop();82 Ok(ExecuteResult {83 user_time,84 system_time,85 status,86 })87}