executor.rs
This file
Path
src/benchmark/executor.rs
350 lines · 10.8 KiB · Rust
Last changed by
Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9
History of this fileTake it
1#[cfg(windows)]2use std::os::windows::process::CommandExt;3use std::process::ExitStatus;45use crate::command::Command;6use crate::options::{7 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,8};9use crate::output::progress_bar::get_progress_bar;10use crate::quantity::{second, Information, Time, Zero};11use crate::timer::execute_and_measure;12use crate::util::randomized_environment_offset;1314use super::measurement::{Measurement, Measurements};1516use anyhow::{bail, Context, Result};1718pub enum BenchmarkIteration {19 NonBenchmarkRun,20 Warmup(u64),21 Benchmark(u64),22}2324impl BenchmarkIteration {25 pub fn to_env_var_value(&self) -> Option<String> {26 match self {27 BenchmarkIteration::NonBenchmarkRun => None,28 BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)),29 BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)),30 }31 }32}3334pub trait Executor {35 /// Run the given command and measure the execution time36 fn run_command_and_measure(37 &self,38 command: &Command<'_>,39 iteration: BenchmarkIteration,40 command_failure_action: Option<CmdFailureAction>,41 output_policy: &CommandOutputPolicy,42 ) -> Result<Measurement>;4344 /// Perform a calibration of this executor. For example,45 /// when running commands through a shell, we need to46 /// measure the shell spawning time separately in order47 /// to subtract it from the full runtime later.48 fn calibrate(&mut self) -> Result<()>;4950 /// Return the time overhead for this executor when51 /// performing a measurement. This should return the time52 /// that is being used in addition to the actual runtime53 /// of the command.54 fn time_overhead(&self) -> Time;55}5657fn run_command_and_measure_common(58 mut command: std::process::Command,59 iteration: BenchmarkIteration,60 command_failure_action: CmdFailureAction,61 command_input_policy: &CommandInputPolicy,62 command_output_policy: &CommandOutputPolicy,63 command_name: &str,64) -> Result<Measurement> {65 let stdin = command_input_policy.get_stdin()?;66 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;67 command.stdin(stdin).stdout(stdout).stderr(stderr);6869 command.env(70 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",71 randomized_environment_offset::value(),72 );7374 if let Some(value) = iteration.to_env_var_value() {75 command.env("HYPERFINE_ITERATION", value);76 }7778 let result = execute_and_measure(command)79 .with_context(|| format!("Failed to run command '{command_name}'"))?;8081 if !result.exit_status.success() {82 use crate::util::exit_code::extract_exit_code;8384 let should_fail = match command_failure_action {85 CmdFailureAction::RaiseError => true,86 CmdFailureAction::IgnoreAllFailures => false,87 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {88 // Only fail if the exit code is not in the list of codes to ignore89 if let Some(exit_code) = extract_exit_code(result.exit_status) {90 !codes.contains(&exit_code)91 } else {92 // If we can't extract an exit code, treat it as a failure93 true94 }95 }96 };9798 if should_fail {99 let when = match iteration {100 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),101 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),102 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),103 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),104 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),105 };106 bail!(107 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \108 Alternatively, use the '--show-output' option to debug what went wrong.",109 cause=result.exit_status.code().map_or(110 "The process has been terminated by a signal".into(),111 |c| format!("Command terminated with non-zero exit code {c}")112113 ),114 );115 }116 }117118 Ok(result)119}120121pub struct RawExecutor<'a> {122 options: &'a Options,123}124125impl<'a> RawExecutor<'a> {126 pub fn new(options: &'a Options) -> Self {127 RawExecutor { options }128 }129}130131impl Executor for RawExecutor<'_> {132 fn run_command_and_measure(133 &self,134 command: &Command<'_>,135 iteration: BenchmarkIteration,136 command_failure_action: Option<CmdFailureAction>,137 output_policy: &CommandOutputPolicy,138 ) -> Result<Measurement> {139 run_command_and_measure_common(140 command.get_command()?,141 iteration,142 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),143 &self.options.command_input_policy,144 output_policy,145 &command.get_command_line(),146 )147 }148149 fn calibrate(&mut self) -> Result<()> {150 Ok(())151 }152153 fn time_overhead(&self) -> Time {154 Time::zero()155 }156}157158pub struct ShellExecutor<'a> {159 options: &'a Options,160 shell: &'a Shell,161 shell_spawning_time: Option<Measurement>,162}163164impl<'a> ShellExecutor<'a> {165 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {166 ShellExecutor {167 shell,168 options,169 shell_spawning_time: None,170 }171 }172}173174impl Executor for ShellExecutor<'_> {175 fn run_command_and_measure(176 &self,177 command: &Command<'_>,178 iteration: BenchmarkIteration,179 command_failure_action: Option<CmdFailureAction>,180 output_policy: &CommandOutputPolicy,181 ) -> Result<Measurement> {182 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");183 let mut command_builder = self.shell.command();184 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });185186 // Windows needs special treatment for its behavior on parsing cmd arguments187 if on_windows_cmd {188 #[cfg(windows)]189 command_builder.raw_arg(command.get_command_line());190 } else {191 command_builder.arg(command.get_command_line());192 }193194 let mut result = run_command_and_measure_common(195 command_builder,196 iteration,197 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),198 &self.options.command_input_policy,199 output_policy,200 &command.get_command_line(),201 )?;202203 // Subtract shell spawning time204 if let Some(spawning_time) = self.shell_spawning_time {205 result.time_wall_clock =206 (result.time_wall_clock - spawning_time.time_wall_clock).max(Time::zero());207 result.time_user = (result.time_user - spawning_time.time_user).max(Time::zero());208 result.time_system = (result.time_system - spawning_time.time_system).max(Time::zero());209 }210211 Ok(result)212 }213214 /// Measure the average shell spawning time215 fn calibrate(&mut self) -> Result<()> {216 const COUNT: u64 = 50;217 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {218 Some(get_progress_bar(219 COUNT,220 "Measuring shell spawning time",221 self.options.output_style,222 ))223 } else {224 None225 };226227 let mut measurements = Measurements::default();228229 for _ in 0..COUNT {230 // Just run the shell without any command231 let res = self.run_command_and_measure(232 &Command::new(None, ""),233 BenchmarkIteration::NonBenchmarkRun,234 None,235 &CommandOutputPolicy::Null,236 );237238 match res {239 Err(_) => {240 let shell_cmd = if cfg!(windows) {241 format!("{} /C \"\"", self.shell)242 } else {243 format!("{} -c \"\"", self.shell)244 };245246 bail!(247 "Could not measure shell execution time. Make sure you can run '{}'.",248 shell_cmd249 );250 }251 Ok(r) => {252 measurements.push(r);253 }254 }255256 if let Some(bar) = progress_bar.as_ref() {257 bar.inc(1)258 }259 }260261 if let Some(bar) = progress_bar.as_ref() {262 bar.finish_and_clear()263 }264265 self.shell_spawning_time = Some(Measurement {266 time_wall_clock: measurements.time_wall_clock_mean(),267 time_user: measurements.time_user_mean(),268 time_system: measurements.time_system_mean(),269 peak_memory_usage: measurements.peak_memory_usage_mean(),270 exit_status: ExitStatus::default(),271 });272273 Ok(())274 }275276 fn time_overhead(&self) -> Time {277 self.shell_spawning_time.unwrap().time_wall_clock278 }279}280281#[derive(Clone)]282pub struct MockExecutor {283 shell: Option<String>,284}285286impl MockExecutor {287 pub fn new(shell: Option<String>) -> Self {288 MockExecutor { shell }289 }290291 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {292 assert!(sleep_command.as_ref().starts_with("sleep "));293 Time::new::<second>(294 sleep_command295 .as_ref()296 .trim_start_matches("sleep ")297 .parse::<f64>()298 .unwrap(),299 )300 }301}302303impl Executor for MockExecutor {304 fn run_command_and_measure(305 &self,306 command: &Command<'_>,307 _iteration: BenchmarkIteration,308 _command_failure_action: Option<CmdFailureAction>,309 _output_policy: &CommandOutputPolicy,310 ) -> Result<Measurement> {311 #[cfg(unix)]312 let exit_status = {313 use std::os::unix::process::ExitStatusExt;314 ExitStatus::from_raw(0)315 };316317 #[cfg(windows)]318 let exit_status = {319 use std::os::windows::process::ExitStatusExt;320 ExitStatus::from_raw(0)321 };322323 Ok(Measurement {324 time_wall_clock: Self::extract_time(command.get_command_line()),325 time_user: Time::zero(),326 time_system: Time::zero(),327 peak_memory_usage: Information::zero(),328 exit_status,329 })330 }331332 fn calibrate(&mut self) -> Result<()> {333 Ok(())334 }335336 fn time_overhead(&self) -> Time {337 match &self.shell {338 None => Time::zero(),339 Some(shell) => Self::extract_time(shell),340 }341 }342}343344#[test]345fn test_mock_executor_extract_time() {346 assert_eq!(347 MockExecutor::extract_time("sleep 0.1"),348 Time::new::<second>(0.1)349 );350}