Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

249 lines · 7.6 KiB · Rust

Last changed by

Further simplify execute_and_measureDavid Peterbefore adoptione1da8ba

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, wall_clock_timer::WallClockTimer};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}3536pub struct ShellExecutor<'a> {37    options: &'a Options,38    shell: &'a Shell,39    shell_spawning_time: Option<TimingResult>,40}4142impl<'a> ShellExecutor<'a> {43    fn subtract_shell_spawning_time(&self, time: Second, shell_spawning_time: Second) -> Second {44        if time < shell_spawning_time {45            0.046        } else {47            time - shell_spawning_time48        }49    }5051    pub fn new(shell: &'a Shell, options: &'a Options) -> Self {52        ShellExecutor {53            shell,54            options,55            shell_spawning_time: None,56        }57    }58}5960impl<'a> Executor for ShellExecutor<'a> {61    fn run_command_and_measure(62        &self,63        command: &Command<'_>,64        command_failure_action: Option<CmdFailureAction>,65    ) -> Result<(TimingResult, ExitStatus)> {66        let (stdout, stderr) = match self.options.command_output_policy {67            CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),68            CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),69        };7071        let mut command_builder = self.shell.command();72        command_builder73            .arg(if cfg!(windows) { "/C" } else { "-c" })74            .arg(command.get_command_line())75            .env(76                "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",77                randomized_environment_offset::value(),78            )79            .stdin(Stdio::null())80            .stdout(stdout)81            .stderr(stderr);8283        let wallclock_timer = WallClockTimer::start();84        let result = execute_and_measure(command_builder)85            .with_context(|| format!("Failed to run command '{}'", command.get_command_line()))?;86        let mut time_real = wallclock_timer.stop();8788        let mut time_user = result.user_time;89        let mut time_system = result.system_time;9091        if command_failure_action.unwrap_or(self.options.command_failure_action)92            == CmdFailureAction::RaiseError93            && !result.status.success()94        {95            bail!(96                "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \97                Alternatively, use the '--show-output' option to debug what went wrong.",98                result.status.code().map_or(99                    "The process has been terminated by a signal".into(),100                    |c| format!("Command terminated with non-zero exit code: {}", c)101                )102            );103        }104105        // Subtract shell spawning time106        if let Some(spawning_time) = self.shell_spawning_time {107            time_real = self.subtract_shell_spawning_time(time_real, spawning_time.time_real);108            time_user = self.subtract_shell_spawning_time(time_user, spawning_time.time_user);109            time_system = self.subtract_shell_spawning_time(time_system, spawning_time.time_system);110        }111112        Ok((113            TimingResult {114                time_real,115                time_user,116                time_system,117            },118            result.status,119        ))120    }121122    /// Measure the average shell spawning time123    fn calibrate(&mut self) -> Result<()> {124        const COUNT: u64 = 50;125        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {126            Some(get_progress_bar(127                COUNT,128                "Measuring shell spawning time",129                self.options.output_style,130            ))131        } else {132            None133        };134135        let mut times_real: Vec<Second> = vec![];136        let mut times_user: Vec<Second> = vec![];137        let mut times_system: Vec<Second> = vec![];138139        for _ in 0..COUNT {140            // Just run the shell without any command141            let res = self.run_command_and_measure(&Command::new(None, ""), None);142143            match res {144                Err(_) => {145                    let shell_cmd = if cfg!(windows) {146                        format!("{} /C \"\"", self.shell)147                    } else {148                        format!("{} -c \"\"", self.shell)149                    };150151                    bail!(152                        "Could not measure shell execution time. Make sure you can run '{}'.",153                        shell_cmd154                    );155                }156                Ok((r, _)) => {157                    times_real.push(r.time_real);158                    times_user.push(r.time_user);159                    times_system.push(r.time_system);160                }161            }162163            if let Some(bar) = progress_bar.as_ref() {164                bar.inc(1)165            }166        }167168        if let Some(bar) = progress_bar.as_ref() {169            bar.finish_and_clear()170        }171172        self.shell_spawning_time = Some(TimingResult {173            time_real: mean(&times_real),174            time_user: mean(&times_user),175            time_system: mean(&times_system),176        });177178        Ok(())179    }180181    fn time_overhead(&self) -> Second {182        self.shell_spawning_time.unwrap().time_real183    }184}185186#[derive(Clone)]187pub struct MockExecutor {188    shell: Option<String>,189}190191impl MockExecutor {192    pub fn new(shell: Option<String>) -> Self {193        MockExecutor { shell }194    }195196    fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {197        assert!(sleep_command.as_ref().starts_with("sleep "));198        sleep_command199            .as_ref()200            .trim_start_matches("sleep ")201            .parse::<Second>()202            .unwrap()203    }204}205206impl Executor for MockExecutor {207    fn run_command_and_measure(208        &self,209        command: &Command<'_>,210        _command_failure_action: Option<CmdFailureAction>,211    ) -> Result<(TimingResult, ExitStatus)> {212        #[cfg(unix)]213        let status = {214            use std::os::unix::process::ExitStatusExt;215            ExitStatus::from_raw(0)216        };217218        #[cfg(windows)]219        let status = {220            use std::os::windows::process::ExitStatusExt;221            ExitStatus::from_raw(0)222        };223224        Ok((225            TimingResult {226                time_real: Self::extract_time(command.get_command_line()),227                time_user: 0.0,228                time_system: 0.0,229            },230            status,231        ))232    }233234    fn calibrate(&mut self) -> Result<()> {235        Ok(())236    }237238    fn time_overhead(&self) -> Second {239        match &self.shell {240            None => 0.0,241            Some(shell) => Self::extract_time(shell),242        }243    }244}245246#[test]247fn test_mock_executor_extract_time() {248    assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);249}