Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

301 lines · 8.9 KiB · Rust

Last changed by

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

History of this file

Take it

1#[cfg(windows)]2use std::os::windows::process::CommandExt;3use std::process::ExitStatus;45use crate::command::Command;6use crate::options::{7    CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,8};9use crate::output::progress_bar::get_progress_bar;10use crate::timer::{execute_and_measure, TimerResult};11use crate::util::randomized_environment_offset;12use crate::util::units::Second;1314use super::timing_result::TimingResult;1516use anyhow::{bail, Context, Result};17use statistical::mean;1819pub trait Executor {20    /// Run the given command and measure the execution time21    fn run_command_and_measure(22        &self,23        command: &Command<'_>,24        command_failure_action: Option<CmdFailureAction>,25    ) -> Result<(TimingResult, ExitStatus)>;2627    /// Perform a calibration of this executor. For example,28    /// when running commands through a shell, we need to29    /// measure the shell spawning time separately in order30    /// to subtract it from the full runtime later.31    fn calibrate(&mut self) -> Result<()>;3233    /// Return the time overhead for this executor when34    /// performing a measurement. This should return the time35    /// that is being used in addition to the actual runtime36    /// of the command.37    fn time_overhead(&self) -> Second;38}3940fn run_command_and_measure_common(41    mut command: std::process::Command,42    command_failure_action: CmdFailureAction,43    command_input_policy: &CommandInputPolicy,44    command_output_policy: &CommandOutputPolicy,45    command_name: &str,46) -> Result<TimerResult> {47    let stdin = command_input_policy.get_stdin()?;48    let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;49    command.stdin(stdin).stdout(stdout).stderr(stderr);5051    command.env(52        "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",53        randomized_environment_offset::value(),54    );5556    let result = execute_and_measure(command)57        .with_context(|| format!("Failed to run command '{}'", command_name))?;5859    if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {60        bail!(61            "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \62            Alternatively, use the '--show-output' option to debug what went wrong.",63            result.status.code().map_or(64                "The process has been terminated by a signal".into(),65                |c| format!("Command terminated with non-zero exit code: {}", c)66            )67        );68    }6970    Ok(result)71}7273pub struct RawExecutor<'a> {74    options: &'a Options,75}7677impl<'a> RawExecutor<'a> {78    pub fn new(options: &'a Options) -> Self {79        RawExecutor { options }80    }81}8283impl<'a> Executor for RawExecutor<'a> {84    fn run_command_and_measure(85        &self,86        command: &Command<'_>,87        command_failure_action: Option<CmdFailureAction>,88    ) -> Result<(TimingResult, ExitStatus)> {89        let result = run_command_and_measure_common(90            command.get_command()?,91            command_failure_action.unwrap_or(self.options.command_failure_action),92            &self.options.command_input_policy,93            &self.options.command_output_policy,94            &command.get_command_line(),95        )?;9697        Ok((98            TimingResult {99                time_real: result.time_real,100                time_user: result.time_user,101                time_system: result.time_system,102            },103            result.status,104        ))105    }106107    fn calibrate(&mut self) -> Result<()> {108        Ok(())109    }110111    fn time_overhead(&self) -> Second {112        0.0113    }114}115116pub struct ShellExecutor<'a> {117    options: &'a Options,118    shell: &'a Shell,119    shell_spawning_time: Option<TimingResult>,120}121122impl<'a> ShellExecutor<'a> {123    pub fn new(shell: &'a Shell, options: &'a Options) -> Self {124        ShellExecutor {125            shell,126            options,127            shell_spawning_time: None,128        }129    }130}131132impl<'a> Executor for ShellExecutor<'a> {133    fn run_command_and_measure(134        &self,135        command: &Command<'_>,136        command_failure_action: Option<CmdFailureAction>,137    ) -> Result<(TimingResult, ExitStatus)> {138        let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");139        let mut command_builder = self.shell.command();140        command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });141142        // Windows needs special treatment for its behavior on parsing cmd arguments143        if on_windows_cmd {144            command_builder.raw_arg(command.get_command_line());145        } else {146            command_builder.arg(command.get_command_line());147        }148149        let mut result = run_command_and_measure_common(150            command_builder,151            command_failure_action.unwrap_or(self.options.command_failure_action),152            &self.options.command_input_policy,153            &self.options.command_output_policy,154            &command.get_command_line(),155        )?;156157        // Subtract shell spawning time158        if let Some(spawning_time) = self.shell_spawning_time {159            result.time_real = (result.time_real - spawning_time.time_real).max(0.0);160            result.time_user = (result.time_user - spawning_time.time_user).max(0.0);161            result.time_system = (result.time_system - spawning_time.time_system).max(0.0);162        }163164        Ok((165            TimingResult {166                time_real: result.time_real,167                time_user: result.time_user,168                time_system: result.time_system,169            },170            result.status,171        ))172    }173174    /// Measure the average shell spawning time175    fn calibrate(&mut self) -> Result<()> {176        const COUNT: u64 = 50;177        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {178            Some(get_progress_bar(179                COUNT,180                "Measuring shell spawning time",181                self.options.output_style,182            ))183        } else {184            None185        };186187        let mut times_real: Vec<Second> = vec![];188        let mut times_user: Vec<Second> = vec![];189        let mut times_system: Vec<Second> = vec![];190191        for _ in 0..COUNT {192            // Just run the shell without any command193            let res = self.run_command_and_measure(&Command::new(None, ""), None);194195            match res {196                Err(_) => {197                    let shell_cmd = if cfg!(windows) {198                        format!("{} /C \"\"", self.shell)199                    } else {200                        format!("{} -c \"\"", self.shell)201                    };202203                    bail!(204                        "Could not measure shell execution time. Make sure you can run '{}'.",205                        shell_cmd206                    );207                }208                Ok((r, _)) => {209                    times_real.push(r.time_real);210                    times_user.push(r.time_user);211                    times_system.push(r.time_system);212                }213            }214215            if let Some(bar) = progress_bar.as_ref() {216                bar.inc(1)217            }218        }219220        if let Some(bar) = progress_bar.as_ref() {221            bar.finish_and_clear()222        }223224        self.shell_spawning_time = Some(TimingResult {225            time_real: mean(&times_real),226            time_user: mean(&times_user),227            time_system: mean(&times_system),228        });229230        Ok(())231    }232233    fn time_overhead(&self) -> Second {234        self.shell_spawning_time.unwrap().time_real235    }236}237238#[derive(Clone)]239pub struct MockExecutor {240    shell: Option<String>,241}242243impl MockExecutor {244    pub fn new(shell: Option<String>) -> Self {245        MockExecutor { shell }246    }247248    fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {249        assert!(sleep_command.as_ref().starts_with("sleep "));250        sleep_command251            .as_ref()252            .trim_start_matches("sleep ")253            .parse::<Second>()254            .unwrap()255    }256}257258impl Executor for MockExecutor {259    fn run_command_and_measure(260        &self,261        command: &Command<'_>,262        _command_failure_action: Option<CmdFailureAction>,263    ) -> Result<(TimingResult, ExitStatus)> {264        #[cfg(unix)]265        let status = {266            use std::os::unix::process::ExitStatusExt;267            ExitStatus::from_raw(0)268        };269270        #[cfg(windows)]271        let status = {272            use std::os::windows::process::ExitStatusExt;273            ExitStatus::from_raw(0)274        };275276        Ok((277            TimingResult {278                time_real: Self::extract_time(command.get_command_line()),279                time_user: 0.0,280                time_system: 0.0,281            },282            status,283        ))284    }285286    fn calibrate(&mut self) -> Result<()> {287        Ok(())288    }289290    fn time_overhead(&self) -> Second {291        match &self.shell {292            None => 0.0,293            Some(shell) => Self::extract_time(shell),294        }295    }296}297298#[test]299fn test_mock_executor_extract_time() {300    assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);301}