Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

245 lines · 7.3 KiB · Rust

Last changed by

Extract common functionalityDavid Peterbefore adoption308bf5c

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 ShellExecutor<'a> {68    options: &'a Options,69    shell: &'a Shell,70    shell_spawning_time: Option<TimingResult>,71}7273impl<'a> ShellExecutor<'a> {74    pub fn new(shell: &'a Shell, options: &'a Options) -> Self {75        ShellExecutor {76            shell,77            options,78            shell_spawning_time: None,79        }80    }81}8283impl<'a> Executor for ShellExecutor<'a> {84    fn run_command_and_measure(85        &self,86        command: &Command<'_>,87        command_failure_action: Option<CmdFailureAction>,88    ) -> Result<(TimingResult, ExitStatus)> {89        let mut command_builder = self.shell.command();90        command_builder91            .arg(if cfg!(windows) { "/C" } else { "-c" })92            .arg(command.get_command_line());9394        let mut result = run_command_and_measure_common(95            command_builder,96            command_failure_action.unwrap_or(self.options.command_failure_action),97            self.options.command_output_policy,98            &command.get_command_line(),99        )?;100101        // Subtract shell spawning time102        if let Some(spawning_time) = self.shell_spawning_time {103            result.time_real = (result.time_real - spawning_time.time_real).max(0.0);104            result.time_user = (result.time_user - spawning_time.time_user).max(0.0);105            result.time_system = (result.time_system - spawning_time.time_system).max(0.0);106        }107108        Ok((109            TimingResult {110                time_real: result.time_real,111                time_user: result.time_user,112                time_system: result.time_system,113            },114            result.status,115        ))116    }117118    /// Measure the average shell spawning time119    fn calibrate(&mut self) -> Result<()> {120        const COUNT: u64 = 50;121        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {122            Some(get_progress_bar(123                COUNT,124                "Measuring shell spawning time",125                self.options.output_style,126            ))127        } else {128            None129        };130131        let mut times_real: Vec<Second> = vec![];132        let mut times_user: Vec<Second> = vec![];133        let mut times_system: Vec<Second> = vec![];134135        for _ in 0..COUNT {136            // Just run the shell without any command137            let res = self.run_command_and_measure(&Command::new(None, ""), None);138139            match res {140                Err(_) => {141                    let shell_cmd = if cfg!(windows) {142                        format!("{} /C \"\"", self.shell)143                    } else {144                        format!("{} -c \"\"", self.shell)145                    };146147                    bail!(148                        "Could not measure shell execution time. Make sure you can run '{}'.",149                        shell_cmd150                    );151                }152                Ok((r, _)) => {153                    times_real.push(r.time_real);154                    times_user.push(r.time_user);155                    times_system.push(r.time_system);156                }157            }158159            if let Some(bar) = progress_bar.as_ref() {160                bar.inc(1)161            }162        }163164        if let Some(bar) = progress_bar.as_ref() {165            bar.finish_and_clear()166        }167168        self.shell_spawning_time = Some(TimingResult {169            time_real: mean(&times_real),170            time_user: mean(&times_user),171            time_system: mean(&times_system),172        });173174        Ok(())175    }176177    fn time_overhead(&self) -> Second {178        self.shell_spawning_time.unwrap().time_real179    }180}181182#[derive(Clone)]183pub struct MockExecutor {184    shell: Option<String>,185}186187impl MockExecutor {188    pub fn new(shell: Option<String>) -> Self {189        MockExecutor { shell }190    }191192    fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {193        assert!(sleep_command.as_ref().starts_with("sleep "));194        sleep_command195            .as_ref()196            .trim_start_matches("sleep ")197            .parse::<Second>()198            .unwrap()199    }200}201202impl Executor for MockExecutor {203    fn run_command_and_measure(204        &self,205        command: &Command<'_>,206        _command_failure_action: Option<CmdFailureAction>,207    ) -> Result<(TimingResult, ExitStatus)> {208        #[cfg(unix)]209        let status = {210            use std::os::unix::process::ExitStatusExt;211            ExitStatus::from_raw(0)212        };213214        #[cfg(windows)]215        let status = {216            use std::os::windows::process::ExitStatusExt;217            ExitStatus::from_raw(0)218        };219220        Ok((221            TimingResult {222                time_real: Self::extract_time(command.get_command_line()),223                time_user: 0.0,224                time_system: 0.0,225            },226            status,227        ))228    }229230    fn calibrate(&mut self) -> Result<()> {231        Ok(())232    }233234    fn time_overhead(&self) -> Second {235        match &self.shell {236            None => 0.0,237            Some(shell) => Self::extract_time(shell),238        }239    }240}241242#[test]243fn test_mock_executor_extract_time() {244    assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);245}