Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

297 lines · 8.7 KiB · Rust

Last changed by

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

History of this file

Take it

1use std::process::{ExitStatus, Stdio};23use crate::command::Command;4use crate::options::{CmdFailureAction, CommandInputPolicy, 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_input_policy: &CommandInputPolicy,40    command_output_policy: &CommandOutputPolicy,41    command_name: &str,42) -> Result<TimerResult> {43    let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;44    let stdin = command_input_policy.get_stdin()?;45    command.stdin(stdin).stdout(stdout).stderr(stderr);4647    command.env(48        "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",49        randomized_environment_offset::value(),50    );5152    let result = execute_and_measure(command)53        .with_context(|| format!("Failed to run command '{}'", command_name))?;5455    if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {56        bail!(57            "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \58            Alternatively, use the '--show-output' option to debug what went wrong.",59            result.status.code().map_or(60                "The process has been terminated by a signal".into(),61                |c| format!("Command terminated with non-zero exit code: {}", c)62            )63        );64    }6566    Ok(result)67}6869pub struct RawExecutor<'a> {70    options: &'a Options,71}7273impl<'a> RawExecutor<'a> {74    pub fn new(options: &'a Options) -> Self {75        RawExecutor { options }76    }77}7879impl<'a> Executor for RawExecutor<'a> {80    fn run_command_and_measure(81        &self,82        command: &Command<'_>,83        command_failure_action: Option<CmdFailureAction>,84    ) -> Result<(TimingResult, ExitStatus)> {85        let result = run_command_and_measure_common(86            command.get_command()?,87            command_failure_action.unwrap_or(self.options.command_failure_action),88            &self.options.command_input_policy,89            &self.options.command_output_policy,90            &command.get_command_line(),91        )?;9293        Ok((94            TimingResult {95                time_real: result.time_real,96                time_user: result.time_user,97                time_system: result.time_system,98            },99            result.status,100        ))101    }102103    fn calibrate(&mut self) -> Result<()> {104        Ok(())105    }106107    fn time_overhead(&self) -> Second {108        0.0109    }110}111112pub struct ShellExecutor<'a> {113    options: &'a Options,114    shell: &'a Shell,115    shell_spawning_time: Option<TimingResult>,116}117118impl<'a> ShellExecutor<'a> {119    pub fn new(shell: &'a Shell, options: &'a Options) -> Self {120        ShellExecutor {121            shell,122            options,123            shell_spawning_time: None,124        }125    }126}127128impl<'a> Executor for ShellExecutor<'a> {129    fn run_command_and_measure(130        &self,131        command: &Command<'_>,132        command_failure_action: Option<CmdFailureAction>,133    ) -> Result<(TimingResult, ExitStatus)> {134        let mut command_builder = self.shell.command();135        command_builder136            .arg(137                if cfg!(windows) && *self.shell == Shell::Default("cmd.exe") {138                    "/C"139                } else {140                    "-c"141                },142            )143            .arg(command.get_command_line());144145        let mut result = run_command_and_measure_common(146            command_builder,147            command_failure_action.unwrap_or(self.options.command_failure_action),148            &self.options.command_input_policy,149            &self.options.command_output_policy,150            &command.get_command_line(),151        )?;152153        // Subtract shell spawning time154        if let Some(spawning_time) = self.shell_spawning_time {155            result.time_real = (result.time_real - spawning_time.time_real).max(0.0);156            result.time_user = (result.time_user - spawning_time.time_user).max(0.0);157            result.time_system = (result.time_system - spawning_time.time_system).max(0.0);158        }159160        Ok((161            TimingResult {162                time_real: result.time_real,163                time_user: result.time_user,164                time_system: result.time_system,165            },166            result.status,167        ))168    }169170    /// Measure the average shell spawning time171    fn calibrate(&mut self) -> Result<()> {172        const COUNT: u64 = 50;173        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {174            Some(get_progress_bar(175                COUNT,176                "Measuring shell spawning time",177                self.options.output_style,178            ))179        } else {180            None181        };182183        let mut times_real: Vec<Second> = vec![];184        let mut times_user: Vec<Second> = vec![];185        let mut times_system: Vec<Second> = vec![];186187        for _ in 0..COUNT {188            // Just run the shell without any command189            let res = self.run_command_and_measure(&Command::new(None, ""), None);190191            match res {192                Err(_) => {193                    let shell_cmd = if cfg!(windows) {194                        format!("{} /C \"\"", self.shell)195                    } else {196                        format!("{} -c \"\"", self.shell)197                    };198199                    bail!(200                        "Could not measure shell execution time. Make sure you can run '{}'.",201                        shell_cmd202                    );203                }204                Ok((r, _)) => {205                    times_real.push(r.time_real);206                    times_user.push(r.time_user);207                    times_system.push(r.time_system);208                }209            }210211            if let Some(bar) = progress_bar.as_ref() {212                bar.inc(1)213            }214        }215216        if let Some(bar) = progress_bar.as_ref() {217            bar.finish_and_clear()218        }219220        self.shell_spawning_time = Some(TimingResult {221            time_real: mean(&times_real),222            time_user: mean(&times_user),223            time_system: mean(&times_system),224        });225226        Ok(())227    }228229    fn time_overhead(&self) -> Second {230        self.shell_spawning_time.unwrap().time_real231    }232}233234#[derive(Clone)]235pub struct MockExecutor {236    shell: Option<String>,237}238239impl MockExecutor {240    pub fn new(shell: Option<String>) -> Self {241        MockExecutor { shell }242    }243244    fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {245        assert!(sleep_command.as_ref().starts_with("sleep "));246        sleep_command247            .as_ref()248            .trim_start_matches("sleep ")249            .parse::<Second>()250            .unwrap()251    }252}253254impl Executor for MockExecutor {255    fn run_command_and_measure(256        &self,257        command: &Command<'_>,258        _command_failure_action: Option<CmdFailureAction>,259    ) -> Result<(TimingResult, ExitStatus)> {260        #[cfg(unix)]261        let status = {262            use std::os::unix::process::ExitStatusExt;263            ExitStatus::from_raw(0)264        };265266        #[cfg(windows)]267        let status = {268            use std::os::windows::process::ExitStatusExt;269            ExitStatus::from_raw(0)270        };271272        Ok((273            TimingResult {274                time_real: Self::extract_time(command.get_command_line()),275                time_user: 0.0,276                time_system: 0.0,277            },278            status,279        ))280    }281282    fn calibrate(&mut self) -> Result<()> {283        Ok(())284    }285286    fn time_overhead(&self) -> Second {287        match &self.shell {288            None => 0.0,289            Some(shell) => Self::extract_time(shell),290        }291    }292}293294#[test]295fn test_mock_executor_extract_time() {296    assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);297}