Skip to content
Myr

shell.rs

This file

Path

src/shell.rs

96 lines · 2.2 KiB · Rust

Last changed by

Flat directory/module structureDavid Peterbefore adoption30c381f

History of this file

Take it

1use std::io;2use std::process::{Command, ExitStatus, Stdio};34use crate::timer::get_cpu_timer;56/// Used to indicate the result of running a command7#[derive(Debug, Copy, Clone)]8pub struct ExecuteResult {9    /// The amount of user time the process used10    pub user_time: f64,1112    /// The amount of cpu time the process used13    pub system_time: f64,1415    /// The exit status of the process16    pub status: ExitStatus,17}1819/// Execute the given command and return a timing summary20#[cfg(windows)]21pub fn execute_and_time(22    stdout: Stdio,23    stderr: Stdio,24    command: &str,25    shell: &str,26) -> io::Result<ExecuteResult> {27    let mut child = run_shell_command(stdout, stderr, command, shell)?;28    let cpu_timer = get_cpu_timer(&child);29    let status = child.wait()?;3031    let (user_time, system_time) = cpu_timer.stop();32    Ok(ExecuteResult {33        user_time,34        system_time,35        status,36    })37}3839/// Execute the given command and return a timing summary40#[cfg(not(windows))]41pub fn execute_and_time(42    stdout: Stdio,43    stderr: Stdio,44    command: &str,45    shell: &str,46) -> io::Result<ExecuteResult> {47    let cpu_timer = get_cpu_timer();4849    let status = run_shell_command(stdout, stderr, command, shell)?;5051    let (user_time, system_time) = cpu_timer.stop();5253    Ok(ExecuteResult {54        user_time,55        system_time,56        status,57    })58}5960/// Run a standard shell command using `sh -c`61#[cfg(not(windows))]62fn run_shell_command(63    stdout: Stdio,64    stderr: Stdio,65    command: &str,66    shell: &str,67) -> io::Result<std::process::ExitStatus> {68    Command::new(shell)69        .arg("-c")70        .arg(command)71        .env(72            "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",73            "X".repeat(rand::random::<usize>() % 4096usize),74        )75        .stdin(Stdio::null())76        .stdout(stdout)77        .stderr(stderr)78        .status()79}8081/// Run a Windows shell command using `cmd.exe /C`82#[cfg(windows)]83fn run_shell_command(84    stdout: Stdio,85    stderr: Stdio,86    command: &str,87    shell: &str,88) -> io::Result<std::process::Child> {89    Command::new(shell)90        .arg("/C")91        .arg(command)92        .stdin(Stdio::null())93        .stdout(stdout)94        .stderr(stderr)95        .spawn()96}