Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

307 lines · 9.0 KiB · Rust

Last changed by

bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea

History of this file

Take it

1use std::os::windows::process::CommandExt;2use std::process::ExitStatus;34use crate::command::Command;5use crate::options::{6    CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,7};8use crate::output::progress_bar::get_progress_bar;9use crate::timer::{execute_and_measure, TimerResult};10use crate::util::randomized_environment_offset;11use crate::util::units::Second;1213use super::timing_result::TimingResult;1415use anyhow::{bail, Context, Result};16use statistical::mean;1718pub trait Executor {19    /// Run the given command and measure the execution time20    fn run_command_and_measure(21        &self,22        command: &Command<'_>,23        command_failure_action: Option<CmdFailureAction>,24    ) -> Result<(TimingResult, ExitStatus)>;2526    /// Perform a calibration of this executor. For example,27    /// when running commands through a shell, we need to28    /// measure the shell spawning time separately in order29    /// to subtract it from the full runtime later.30    fn calibrate(&mut self) -> Result<()>;3132    /// Return the time overhead for this executor when33    /// performing a measurement. This should return the time34    /// that is being used in addition to the actual runtime35    /// of the command.36    fn time_overhead(&self) -> Second;37}3839fn run_command_and_measure_common(40    mut command: std::process::Command,41    command_failure_action: CmdFailureAction,42    command_input_policy: &CommandInputPolicy,43    command_output_policy: &CommandOutputPolicy,44    command_name: &str,45) -> Result<TimerResult> {46    let stdin = command_input_policy.get_stdin()?;47    let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;48    command.stdin(stdin).stdout(stdout).stderr(stderr);4950    command.env(51        "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",52        randomized_environment_offset::value(),53    );5455    let result = execute_and_measure(command)56        .with_context(|| format!("Failed to run command '{}'", command_name))?;5758    if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {59        bail!(60            "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \61            Alternatively, use the '--show-output' option to debug what went wrong.",62            result.status.code().map_or(63                "The process has been terminated by a signal".into(),64                |c| format!("Command terminated with non-zero exit code: {}", c)65            )66        );67    }6869    Ok(result)70}7172pub struct RawExecutor<'a> {73    options: &'a Options,74}7576impl<'a> RawExecutor<'a> {77    pub fn new(options: &'a Options) -> Self {78        RawExecutor { options }79    }80}8182impl<'a> Executor for RawExecutor<'a> {83    fn run_command_and_measure(84        &self,85        command: &Command<'_>,86        command_failure_action: Option<CmdFailureAction>,87    ) -> Result<(TimingResult, ExitStatus)> {88        let result = run_command_and_measure_common(89            command.get_command()?,90            command_failure_action.unwrap_or(self.options.command_failure_action),91            &self.options.command_input_policy,92            &self.options.command_output_policy,93            &command.get_command_line(),94        )?;9596        Ok((97            TimingResult {98                time_real: result.time_real,99                time_user: result.time_user,100                time_system: result.time_system,101            },102            result.status,103        ))104    }105106    fn calibrate(&mut self) -> Result<()> {107        Ok(())108    }109110    fn time_overhead(&self) -> Second {111        0.0112    }113}114115pub struct ShellExecutor<'a> {116    options: &'a Options,117    shell: &'a Shell,118    shell_spawning_time: Option<TimingResult>,119}120121impl<'a> ShellExecutor<'a> {122    pub fn new(shell: &'a Shell, options: &'a Options) -> Self {123        ShellExecutor {124            shell,125            options,126            shell_spawning_time: None,127        }128    }129}130131impl<'a> Executor for ShellExecutor<'a> {132    fn run_command_and_measure(133        &self,134        command: &Command<'_>,135        command_failure_action: Option<CmdFailureAction>,136    ) -> Result<(TimingResult, ExitStatus)> {137        let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");138        let mut command_builder = self.shell.command();139        command_builder140            .arg(141                if on_windows_cmd {142                    "/C"143                } else {144                    "-c"145                },146            );147148            // Windows needs special treatment for its behavior on parsing cmd arguments149            if on_windows_cmd {150                command_builder.raw_arg(command.get_command_line());151            } else {152                command_builder.arg(command.get_command_line());153            }154155        let mut result = run_command_and_measure_common(156            command_builder,157            command_failure_action.unwrap_or(self.options.command_failure_action),158            &self.options.command_input_policy,159            &self.options.command_output_policy,160            &command.get_command_line(),161        )?;162163        // Subtract shell spawning time164        if let Some(spawning_time) = self.shell_spawning_time {165            result.time_real = (result.time_real - spawning_time.time_real).max(0.0);166            result.time_user = (result.time_user - spawning_time.time_user).max(0.0);167            result.time_system = (result.time_system - spawning_time.time_system).max(0.0);168        }169170        Ok((171            TimingResult {172                time_real: result.time_real,173                time_user: result.time_user,174                time_system: result.time_system,175            },176            result.status,177        ))178    }179180    /// Measure the average shell spawning time181    fn calibrate(&mut self) -> Result<()> {182        const COUNT: u64 = 50;183        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {184            Some(get_progress_bar(185                COUNT,186                "Measuring shell spawning time",187                self.options.output_style,188            ))189        } else {190            None191        };192193        let mut times_real: Vec<Second> = vec![];194        let mut times_user: Vec<Second> = vec![];195        let mut times_system: Vec<Second> = vec![];196197        for _ in 0..COUNT {198            // Just run the shell without any command199            let res = self.run_command_and_measure(&Command::new(None, ""), None);200201            match res {202                Err(_) => {203                    let shell_cmd = if cfg!(windows) {204                        format!("{} /C \"\"", self.shell)205                    } else {206                        format!("{} -c \"\"", self.shell)207                    };208209                    bail!(210                        "Could not measure shell execution time. Make sure you can run '{}'.",211                        shell_cmd212                    );213                }214                Ok((r, _)) => {215                    times_real.push(r.time_real);216                    times_user.push(r.time_user);217                    times_system.push(r.time_system);218                }219            }220221            if let Some(bar) = progress_bar.as_ref() {222                bar.inc(1)223            }224        }225226        if let Some(bar) = progress_bar.as_ref() {227            bar.finish_and_clear()228        }229230        self.shell_spawning_time = Some(TimingResult {231            time_real: mean(&times_real),232            time_user: mean(&times_user),233            time_system: mean(&times_system),234        });235236        Ok(())237    }238239    fn time_overhead(&self) -> Second {240        self.shell_spawning_time.unwrap().time_real241    }242}243244#[derive(Clone)]245pub struct MockExecutor {246    shell: Option<String>,247}248249impl MockExecutor {250    pub fn new(shell: Option<String>) -> Self {251        MockExecutor { shell }252    }253254    fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {255        assert!(sleep_command.as_ref().starts_with("sleep "));256        sleep_command257            .as_ref()258            .trim_start_matches("sleep ")259            .parse::<Second>()260            .unwrap()261    }262}263264impl Executor for MockExecutor {265    fn run_command_and_measure(266        &self,267        command: &Command<'_>,268        _command_failure_action: Option<CmdFailureAction>,269    ) -> Result<(TimingResult, ExitStatus)> {270        #[cfg(unix)]271        let status = {272            use std::os::unix::process::ExitStatusExt;273            ExitStatus::from_raw(0)274        };275276        #[cfg(windows)]277        let status = {278            use std::os::windows::process::ExitStatusExt;279            ExitStatus::from_raw(0)280        };281282        Ok((283            TimingResult {284                time_real: Self::extract_time(command.get_command_line()),285                time_user: 0.0,286                time_system: 0.0,287            },288            status,289        ))290    }291292    fn calibrate(&mut self) -> Result<()> {293        Ok(())294    }295296    fn time_overhead(&self) -> Second {297        match &self.shell {298            None => 0.0,299            Some(shell) => Self::extract_time(shell),300        }301    }302}303304#[test]305fn test_mock_executor_extract_time() {306    assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);307}