Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

388 lines · 12.6 KiB · Rust

Last changed by

Use uomDavid Peterbefore adoption641451a

History of this file

Take it

1#[cfg(windows)]2use std::os::windows::process::CommandExt;3use std::process::ExitStatus;45use crate::benchmark::measurement::Measurement;6use crate::benchmark::measurement::Measurements;7use crate::benchmark::quantity::Information;8use crate::benchmark::quantity::InformationQuantity;9use crate::benchmark::quantity::{Time, TimeQuantity};10use crate::command::Command;11use crate::options::{12    CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,13};14use crate::output::progress_bar::get_progress_bar;15use crate::timer::execute_and_measure;16use crate::util::randomized_environment_offset;1718use anyhow::{bail, Context, Result};1920#[derive(Clone, Copy)]21pub enum BenchmarkIteration {22    NonBenchmarkRun,23    Warmup(u64),24    Benchmark(u64),25}2627impl BenchmarkIteration {28    pub fn to_env_var_value(&self) -> Option<String> {29        match self {30            BenchmarkIteration::NonBenchmarkRun => None,31            BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)),32            BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)),33        }34    }35}3637pub trait Executor {38    /// Run the given command and measure the execution time39    fn run_command_and_measure(40        &self,41        command: &Command<'_>,42        iteration: BenchmarkIteration,43        command_failure_action: Option<CmdFailureAction>,44        output_policy: &CommandOutputPolicy,45    ) -> Result<Measurement>;4647    /// Perform a calibration of this executor. For example,48    /// when running commands through a shell, we need to49    /// measure the shell spawning time separately in order50    /// to subtract it from the full runtime later.51    fn calibrate(&mut self) -> Result<()>;5253    /// Return the time overhead for this executor when54    /// performing a measurement. This should return the time55    /// that is being used in addition to the actual runtime56    /// of the command.57    fn time_overhead(&self) -> Time;58}5960fn run_command_and_measure_common(61    mut command: std::process::Command,62    iteration: BenchmarkIteration,63    command_failure_action: CmdFailureAction,64    command_input_policy: &CommandInputPolicy,65    command_output_policy: &CommandOutputPolicy,66    command_name: &str,67) -> Result<Measurement> {68    let stdin = command_input_policy.get_stdin()?;69    let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;70    command.stdin(stdin).stdout(stdout).stderr(stderr);7172    command.env(73        "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",74        randomized_environment_offset::value(),75    );7677    if let Some(value) = iteration.to_env_var_value() {78        command.env("HYPERFINE_ITERATION", value);79    }8081    let result = execute_and_measure(command)82        .with_context(|| format!("Failed to run command '{command_name}'"))?;8384    if command_failure_action == CmdFailureAction::RaiseError && !result.exit_status.success() {85        let when = match iteration {86            BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),87            BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),88            BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),89            BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),90            BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),91        };92        bail!(93            "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \94            Alternatively, use the '--show-output' option to debug what went wrong.",95            cause=result.exit_status.code().map_or(96                "The process has been terminated by a signal".into(),97                |c| format!("Command terminated with non-zero exit code {c}")9899        let should_fail = match command_failure_action {100            CmdFailureAction::RaiseError => true,101            CmdFailureAction::IgnoreAllFailures => false,102            CmdFailureAction::IgnoreSpecificFailures(ref codes) => {103                // Only fail if the exit code is not in the list of codes to ignore104                if let Some(exit_code) = extract_exit_code(result.exit_status) {105                    !codes.contains(&exit_code)106                } else {107                    // If we can't extract an exit code, treat it as a failure108                    true109                }110            }111        };112113        if should_fail {114            let when = match iteration {115                BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),116                BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),117                BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),118                BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),119                BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),120            };121            bail!(122                "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \123                Alternatively, use the '--show-output' option to debug what went wrong.",124                cause=result.exit_status.code().map_or(125                    "The process has been terminated by a signal".into(),126                    |c| format!("Command terminated with non-zero exit code {c}")127128                ),129            );130        }131    }132133    Ok(result)134}135136pub struct RawExecutor<'a> {137    options: &'a Options,138}139140impl<'a> RawExecutor<'a> {141    pub fn new(options: &'a Options) -> Self {142        RawExecutor { options }143    }144}145146impl Executor for RawExecutor<'_> {147    fn run_command_and_measure(148        &self,149        command: &Command<'_>,150        iteration: BenchmarkIteration,151        command_failure_action: Option<CmdFailureAction>,152        output_policy: &CommandOutputPolicy,153    ) -> Result<Measurement> {154        let result = run_command_and_measure_common(155            command.get_command()?,156            iteration,157            command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),158            &self.options.command_input_policy,159            output_policy,160            &command.get_command_line(),161        )?;162163        Ok(Measurement {164            time_wall_clock: result.time_wall_clock,165            time_user: result.time_user,166            time_system: result.time_system,167            peak_memory_usage: result.peak_memory_usage,168            exit_status: result.exit_status,169        })170    }171172    fn calibrate(&mut self) -> Result<()> {173        Ok(())174    }175176    fn time_overhead(&self) -> Time {177        Time::zero()178    }179}180181pub struct ShellExecutor<'a> {182    options: &'a Options,183    shell: &'a Shell,184    shell_spawning_time: Option<Measurement>,185}186187impl<'a> ShellExecutor<'a> {188    pub fn new(shell: &'a Shell, options: &'a Options) -> Self {189        ShellExecutor {190            shell,191            options,192            shell_spawning_time: None,193        }194    }195}196197impl Executor for ShellExecutor<'_> {198    fn run_command_and_measure(199        &self,200        command: &Command<'_>,201        iteration: BenchmarkIteration,202        command_failure_action: Option<CmdFailureAction>,203        output_policy: &CommandOutputPolicy,204    ) -> Result<Measurement> {205        let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");206        let mut command_builder = self.shell.command();207        command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });208209        // Windows needs special treatment for its behavior on parsing cmd arguments210        if on_windows_cmd {211            #[cfg(windows)]212            command_builder.raw_arg(command.get_command_line());213        } else {214            command_builder.arg(command.get_command_line());215        }216217        let mut result = run_command_and_measure_common(218            command_builder,219            iteration,220            command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),221            &self.options.command_input_policy,222            output_policy,223            &command.get_command_line(),224        )?;225226        // Subtract shell spawning time227        fn ensure_non_negative(time: Time) -> Time {228            if time < Time::zero() {229                Time::zero()230            } else {231                time232            }233        }234235        if let Some(ref spawning_time) = self.shell_spawning_time {236            result.time_wall_clock =237                ensure_non_negative(result.time_wall_clock - spawning_time.time_wall_clock);238            result.time_user = ensure_non_negative(result.time_user - spawning_time.time_user);239            result.time_system =240                ensure_non_negative(result.time_system - spawning_time.time_system);241        }242243        Ok(Measurement {244            time_wall_clock: result.time_wall_clock,245            time_user: result.time_user,246            time_system: result.time_system,247            peak_memory_usage: result.peak_memory_usage,248            exit_status: result.exit_status,249        })250    }251252    /// Measure the average shell spawning time253    fn calibrate(&mut self) -> Result<()> {254        const COUNT: u64 = 50;255        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {256            Some(get_progress_bar(257                COUNT,258                "Measuring shell spawning time",259                self.options.output_style,260            ))261        } else {262            None263        };264265        let mut measurements = Measurements::default();266267        for _ in 0..COUNT {268            // Just run the shell without any command269            let measurement = self.run_command_and_measure(270                &Command::new(None, ""),271                BenchmarkIteration::NonBenchmarkRun,272                None,273                &CommandOutputPolicy::Null,274            );275276            match measurement {277                Err(_) => {278                    let shell_cmd = if cfg!(windows) {279                        format!("{} /C \"\"", self.shell)280                    } else {281                        format!("{} -c \"\"", self.shell)282                    };283284                    bail!(285                        "Could not measure shell execution time. Make sure you can run '{}'.",286                        shell_cmd287                    );288                }289                Ok(result) => {290                    measurements.push(result);291                }292            }293294            if let Some(bar) = progress_bar.as_ref() {295                bar.inc(1)296            }297        }298299        if let Some(bar) = progress_bar.as_ref() {300            bar.finish_and_clear()301        }302303        self.shell_spawning_time = Some(Measurement {304            time_wall_clock: measurements.time_wall_clock_mean(),305            time_user: measurements.time_user_mean(),306            time_system: measurements.time_system_mean(),307            peak_memory_usage: measurements.peak_memory_usage_mean(),308            exit_status: ExitStatus::default(),309        });310311        Ok(())312    }313314    fn time_overhead(&self) -> Time {315        self.shell_spawning_time.as_ref().unwrap().time_wall_clock316    }317}318319#[derive(Clone)]320pub struct MockExecutor {321    shell: Option<String>,322}323324impl MockExecutor {325    pub fn new(shell: Option<String>) -> Self {326        MockExecutor { shell }327    }328329    fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {330        assert!(sleep_command.as_ref().starts_with("sleep "));331        Time::from_seconds(332            sleep_command333                .as_ref()334                .trim_start_matches("sleep ")335                .parse::<f64>()336                .unwrap(),337        )338    }339}340341impl Executor for MockExecutor {342    fn run_command_and_measure(343        &self,344        command: &Command<'_>,345        _iteration: BenchmarkIteration,346        _command_failure_action: Option<CmdFailureAction>,347        _output_policy: &CommandOutputPolicy,348    ) -> Result<Measurement> {349        #[cfg(unix)]350        let exit_status = {351            use std::os::unix::process::ExitStatusExt;352            ExitStatus::from_raw(0)353        };354355        #[cfg(windows)]356        let exit_status = {357            use std::os::windows::process::ExitStatusExt;358            ExitStatus::from_raw(0)359        };360361        Ok(Measurement {362            time_wall_clock: Self::extract_time(command.get_command_line()),363            time_user: Time::zero(),364            time_system: Time::zero(),365            peak_memory_usage: Information::from_bytes(0),366            exit_status,367        })368    }369370    fn calibrate(&mut self) -> Result<()> {371        Ok(())372    }373374    fn time_overhead(&self) -> Time {375        match &self.shell {376            None => Time::zero(),377            Some(shell) => Self::extract_time(shell),378        }379    }380}381382#[test]383fn test_mock_executor_extract_time() {384    assert_eq!(385        MockExecutor::extract_time("sleep 0.1"),386        Time::from_seconds(0.1)387    );388}