Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

293 lines · 8.5 KiB · Rust

Last changed by

Fixes #568FilipAnderssonbefore adoptionf00acf9

History of this file

Take it

1use std::process::{ExitStatus, Stdio};23use crate::command::Command;4use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};5use crate::output::progress_bar::get_progress_bar;6use crate::timer::{execute_and_measure, TimerResult};7use crate::util::randomized_environment_offset;8use crate::util::units::Second;910use super::timing_result::TimingResult;1112use anyhow::{bail, Context, Result};13use statistical::mean;1415pub trait Executor {16    /// Run the given command and measure the execution time17    fn run_command_and_measure(18        &self,19        command: &Command<'_>,20        command_failure_action: Option<CmdFailureAction>,21    ) -> Result<(TimingResult, ExitStatus)>;2223    /// Perform a calibration of this executor. For example,24    /// when running commands through a shell, we need to25    /// measure the shell spawning time separately in order26    /// to subtract it from the full runtime later.27    fn calibrate(&mut self) -> Result<()>;2829    /// Return the time overhead for this executor when30    /// performing a measurement. This should return the time31    /// that is being used in addition to the actual runtime32    /// of the command.33    fn time_overhead(&self) -> Second;34}3536fn run_command_and_measure_common(37    mut command: std::process::Command,38    command_failure_action: CmdFailureAction,39    command_output_policy: &CommandOutputPolicy,40    command_name: &str,41) -> Result<TimerResult> {42    let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;43    command.stdin(Stdio::null()).stdout(stdout).stderr(stderr);4445    command.env(46        "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",47        randomized_environment_offset::value(),48    );4950    let result = execute_and_measure(command)51        .with_context(|| format!("Failed to run command '{}'", command_name))?;5253    if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {54        bail!(55            "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \56            Alternatively, use the '--show-output' option to debug what went wrong.",57            result.status.code().map_or(58                "The process has been terminated by a signal".into(),59                |c| format!("Command terminated with non-zero exit code: {}", c)60            )61        );62    }6364    Ok(result)65}6667pub struct RawExecutor<'a> {68    options: &'a Options,69}7071impl<'a> RawExecutor<'a> {72    pub fn new(options: &'a Options) -> Self {73        RawExecutor { options }74    }75}7677impl<'a> Executor for RawExecutor<'a> {78    fn run_command_and_measure(79        &self,80        command: &Command<'_>,81        command_failure_action: Option<CmdFailureAction>,82    ) -> Result<(TimingResult, ExitStatus)> {83        let result = run_command_and_measure_common(84            command.get_command()?,85            command_failure_action.unwrap_or(self.options.command_failure_action),86            &self.options.command_output_policy,87            &command.get_command_line(),88        )?;8990        Ok((91            TimingResult {92                time_real: result.time_real,93                time_user: result.time_user,94                time_system: result.time_system,95            },96            result.status,97        ))98    }99100    fn calibrate(&mut self) -> Result<()> {101        Ok(())102    }103104    fn time_overhead(&self) -> Second {105        0.0106    }107}108109pub struct ShellExecutor<'a> {110    options: &'a Options,111    shell: &'a Shell,112    shell_spawning_time: Option<TimingResult>,113}114115impl<'a> ShellExecutor<'a> {116    pub fn new(shell: &'a Shell, options: &'a Options) -> Self {117        ShellExecutor {118            shell,119            options,120            shell_spawning_time: None,121        }122    }123}124125impl<'a> Executor for ShellExecutor<'a> {126    fn run_command_and_measure(127        &self,128        command: &Command<'_>,129        command_failure_action: Option<CmdFailureAction>,130    ) -> Result<(TimingResult, ExitStatus)> {131        let mut command_builder = self.shell.command();132        command_builder133            .arg(134                if cfg!(windows) && *self.shell == Shell::Default("cmd.exe") {135                    "/C"136                } else {137                    "-c"138                },139            )140            .arg(command.get_command_line());141142        let mut result = run_command_and_measure_common(143            command_builder,144            command_failure_action.unwrap_or(self.options.command_failure_action),145            &self.options.command_output_policy,146            &command.get_command_line(),147        )?;148149        // Subtract shell spawning time150        if let Some(spawning_time) = self.shell_spawning_time {151            result.time_real = (result.time_real - spawning_time.time_real).max(0.0);152            result.time_user = (result.time_user - spawning_time.time_user).max(0.0);153            result.time_system = (result.time_system - spawning_time.time_system).max(0.0);154        }155156        Ok((157            TimingResult {158                time_real: result.time_real,159                time_user: result.time_user,160                time_system: result.time_system,161            },162            result.status,163        ))164    }165166    /// Measure the average shell spawning time167    fn calibrate(&mut self) -> Result<()> {168        const COUNT: u64 = 50;169        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {170            Some(get_progress_bar(171                COUNT,172                "Measuring shell spawning time",173                self.options.output_style,174            ))175        } else {176            None177        };178179        let mut times_real: Vec<Second> = vec![];180        let mut times_user: Vec<Second> = vec![];181        let mut times_system: Vec<Second> = vec![];182183        for _ in 0..COUNT {184            // Just run the shell without any command185            let res = self.run_command_and_measure(&Command::new(None, ""), None);186187            match res {188                Err(_) => {189                    let shell_cmd = if cfg!(windows) {190                        format!("{} /C \"\"", self.shell)191                    } else {192                        format!("{} -c \"\"", self.shell)193                    };194195                    bail!(196                        "Could not measure shell execution time. Make sure you can run '{}'.",197                        shell_cmd198                    );199                }200                Ok((r, _)) => {201                    times_real.push(r.time_real);202                    times_user.push(r.time_user);203                    times_system.push(r.time_system);204                }205            }206207            if let Some(bar) = progress_bar.as_ref() {208                bar.inc(1)209            }210        }211212        if let Some(bar) = progress_bar.as_ref() {213            bar.finish_and_clear()214        }215216        self.shell_spawning_time = Some(TimingResult {217            time_real: mean(&times_real),218            time_user: mean(&times_user),219            time_system: mean(&times_system),220        });221222        Ok(())223    }224225    fn time_overhead(&self) -> Second {226        self.shell_spawning_time.unwrap().time_real227    }228}229230#[derive(Clone)]231pub struct MockExecutor {232    shell: Option<String>,233}234235impl MockExecutor {236    pub fn new(shell: Option<String>) -> Self {237        MockExecutor { shell }238    }239240    fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {241        assert!(sleep_command.as_ref().starts_with("sleep "));242        sleep_command243            .as_ref()244            .trim_start_matches("sleep ")245            .parse::<Second>()246            .unwrap()247    }248}249250impl Executor for MockExecutor {251    fn run_command_and_measure(252        &self,253        command: &Command<'_>,254        _command_failure_action: Option<CmdFailureAction>,255    ) -> Result<(TimingResult, ExitStatus)> {256        #[cfg(unix)]257        let status = {258            use std::os::unix::process::ExitStatusExt;259            ExitStatus::from_raw(0)260        };261262        #[cfg(windows)]263        let status = {264            use std::os::windows::process::ExitStatusExt;265            ExitStatus::from_raw(0)266        };267268        Ok((269            TimingResult {270                time_real: Self::extract_time(command.get_command_line()),271                time_user: 0.0,272                time_system: 0.0,273            },274            status,275        ))276    }277278    fn calibrate(&mut self) -> Result<()> {279        Ok(())280    }281282    fn time_overhead(&self) -> Second {283        match &self.shell {284            None => 0.0,285            Some(shell) => Self::extract_time(shell),286        }287    }288}289290#[test]291fn test_mock_executor_extract_time() {292    assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);293}