executor.rs
This file
Path
src/benchmark/executor.rs
401 lines · 12.8 KiB · Rust
Last changed by
Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02
History of this fileTake 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::command::Command;8use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};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 anyhow::{bail, Context, Result};1516#[derive(Clone, Copy)]17pub enum BenchmarkIteration {18 NonBenchmarkRun,19 Warmup(u64),20 Benchmark(u64),21}2223impl BenchmarkIteration {24 pub fn to_env_var_value(&self) -> Option<String> {25 match self {26 BenchmarkIteration::NonBenchmarkRun => None,27 BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)),28 BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)),29 }30 }31}3233pub trait Executor {34 /// Run the given command and measure the execution time35 fn run_command_and_measure(36 &self,37 command: &Command<'_>,38 iteration: BenchmarkIteration,39 command_failure_action: Option<CmdFailureAction>,40 output_policy: &CommandOutputPolicy,41 ) -> Result<Measurement>;4243 /// Run a lifecycle command through a shell, always treating failures as errors.44 fn run_intermediate_command_and_measure(45 &self,46 command: &Command<'_>,47 iteration: BenchmarkIteration,48 output_policy: &CommandOutputPolicy,49 ) -> Result<Measurement> {50 self.run_command_and_measure(51 command,52 iteration,53 Some(CmdFailureAction::RaiseError),54 output_policy,55 )56 }5758 /// Perform a calibration of this executor. For example,59 /// when running commands through a shell, we need to60 /// measure the shell spawning time separately in order61 /// to subtract it from the full runtime later.62 fn calibrate(&mut self) -> Result<()>;6364 /// Return the time overhead for this executor when65 /// performing a measurement. This should return the time66 /// that is being used in addition to the actual runtime67 /// of the command.68 fn time_overhead(&self) -> Time;69}7071fn run_command_and_measure_common(72 mut command: std::process::Command,73 iteration: BenchmarkIteration,74 command_failure_action: Option<CmdFailureAction>,75 options: &Options,76 command_output_policy: &CommandOutputPolicy,77 command_name: &str,78 collect_hardware_counters: bool,79) -> Result<Measurement> {80 let stdin = options.command_input_policy.get_stdin()?;81 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;82 command.stdin(stdin).stdout(stdout).stderr(stderr);8384 command.env(85 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",86 randomized_environment_offset::value(),87 );8889 if let Some(value) = iteration.to_env_var_value() {90 command.env("HYPERFINE_ITERATION", value);91 }9293 let measurement = execute_and_measure(command, collect_hardware_counters)94 .with_context(|| format!("Failed to run command '{command_name}'"))?;9596 if !measurement.exit_status.success() {97 use crate::util::exit_code::extract_exit_code;9899 let show_ignore_failure_hint = command_failure_action.is_none();100 let should_fail = match command_failure_action101 .as_ref()102 .unwrap_or(&options.command_failure_action)103 {104 CmdFailureAction::RaiseError => true,105 CmdFailureAction::IgnoreAllFailures => false,106 CmdFailureAction::IgnoreSpecificFailures(codes) => {107 // Only fail if the exit code is not in the list of codes to ignore108 if let Some(exit_code) = extract_exit_code(measurement.exit_status) {109 !codes.contains(&exit_code)110 } else {111 // If we can't extract an exit code, treat it as a failure112 true113 }114 }115 };116117 if should_fail {118 let when = match iteration {119 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),120 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),121 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),122 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),123 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),124 };125 let cause = measurement.exit_status.code().map_or_else(126 || "was terminated by a signal".to_owned(),127 |code| format!("terminated with non-zero exit code {code}"),128 );129 let hint = if show_ignore_failure_hint {130 " Use the '-i'/'--ignore-failure' option if you want to ignore this. \131 Alternatively, use the '--show-output' option to debug what went wrong."132 } else {133 " Use the '--show-output' option to debug what went wrong."134 };135 bail!("Command '{command_name}' {cause} in {when}.{hint}");136 }137 }138139 Ok(measurement)140}141142pub struct RawExecutor<'a> {143 options: &'a Options,144}145146impl<'a> RawExecutor<'a> {147 pub fn new(options: &'a Options) -> Self {148 RawExecutor { options }149 }150}151152impl Executor for RawExecutor<'_> {153 fn run_command_and_measure(154 &self,155 command: &Command<'_>,156 iteration: BenchmarkIteration,157 command_failure_action: Option<CmdFailureAction>,158 output_policy: &CommandOutputPolicy,159 ) -> Result<Measurement> {160 run_command_and_measure_common(161 command.get_command()?,162 iteration,163 command_failure_action,164 self.options,165 output_policy,166 &command.get_command_line(),167 matches!(iteration, BenchmarkIteration::Benchmark(_)),168 )169 }170171 fn run_intermediate_command_and_measure(172 &self,173 command: &Command<'_>,174 iteration: BenchmarkIteration,175 output_policy: &CommandOutputPolicy,176 ) -> Result<Measurement> {177 // Keep shell startup in the hook's duration: raw benchmarks have no178 // calibrated shell overhead to add back when estimating the run count.179 ShellExecutor::new(&Shell::platform_default(), self.options)180 .run_intermediate_command_and_measure(command, iteration, output_policy)181 }182183 fn calibrate(&mut self) -> Result<()> {184 Ok(())185 }186187 fn time_overhead(&self) -> Time {188 Time::zero()189 }190}191192pub struct ShellExecutor<'a> {193 options: &'a Options,194 shell: &'a Shell,195 shell_spawning_time: Option<Measurement>,196}197198impl<'a> ShellExecutor<'a> {199 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {200 ShellExecutor {201 shell,202 options,203 shell_spawning_time: None,204 }205 }206}207208impl Executor for ShellExecutor<'_> {209 fn run_command_and_measure(210 &self,211 command: &Command<'_>,212 iteration: BenchmarkIteration,213 command_failure_action: Option<CmdFailureAction>,214 output_policy: &CommandOutputPolicy,215 ) -> Result<Measurement> {216 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");217 let mut command_builder = self.shell.command();218 command_builder.envs(command.get_environment());219 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });220221 // Windows needs special treatment for its behavior on parsing cmd arguments222 if on_windows_cmd {223 #[cfg(windows)]224 command_builder.raw_arg(command.get_command_line());225 } else {226 command_builder.arg(command.get_command_line());227 }228229 let mut measurement = run_command_and_measure_common(230 command_builder,231 iteration,232 command_failure_action,233 self.options,234 output_policy,235 &command.get_command_line(),236 false,237 )?;238239 // Subtract shell spawning time240 fn ensure_non_negative(time: Time) -> Time {241 if time < Time::zero() {242 Time::zero()243 } else {244 time245 }246 }247248 if let Some(ref spawning_time) = self.shell_spawning_time {249 measurement.time_wall_clock =250 ensure_non_negative(measurement.time_wall_clock - spawning_time.time_wall_clock);251 measurement.time_user =252 ensure_non_negative(measurement.time_user - spawning_time.time_user);253 measurement.time_system =254 ensure_non_negative(measurement.time_system - spawning_time.time_system);255 measurement.time_cpu = measurement.time_user + measurement.time_system;256 }257258 Ok(measurement)259 }260261 /// Measure the average shell spawning time262 fn calibrate(&mut self) -> Result<()> {263 const COUNT: u64 = 50;264 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {265 Some(get_progress_bar(266 COUNT,267 "Measuring shell spawning time",268 self.options.output_style,269 ))270 } else {271 None272 };273274 let mut measurements = Measurements::default();275276 for _ in 0..COUNT {277 // Just run the shell without any command278 let measurement = self.run_command_and_measure(279 &Command::new(None, ""),280 BenchmarkIteration::NonBenchmarkRun,281 None,282 &CommandOutputPolicy::Null,283 );284285 match measurement {286 Err(_) => {287 let shell_cmd = if cfg!(windows) {288 format!("{} /C \"\"", self.shell)289 } else {290 format!("{} -c \"\"", self.shell)291 };292293 bail!(294 "Could not measure shell execution time. Make sure you can run '{}'.",295 shell_cmd296 );297 }298 Ok(result) => {299 measurements.push(result);300 }301 }302303 if let Some(bar) = progress_bar.as_ref() {304 bar.inc(1)305 }306 }307308 if let Some(bar) = progress_bar.as_ref() {309 bar.finish_and_clear()310 }311312 self.shell_spawning_time = Some(Measurement {313 time_wall_clock: measurements.time_wall_clock_mean(),314 time_cpu: measurements.time_user_mean() + measurements.time_system_mean(),315 time_user: measurements.time_user_mean(),316 time_system: measurements.time_system_mean(),317 memory_peak_resident: None,318 hardware_counters: Default::default(),319 exit_status: ExitStatus::default(),320 });321322 Ok(())323 }324325 fn time_overhead(&self) -> Time {326 self.shell_spawning_time.as_ref().unwrap().time_wall_clock327 }328}329330#[derive(Clone)]331pub struct MockExecutor {332 shell: Option<String>,333}334335impl MockExecutor {336 pub fn new(shell: Option<String>) -> Self {337 MockExecutor { shell }338 }339340 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {341 assert!(sleep_command.as_ref().starts_with("sleep "));342 Time::new::<second>(343 sleep_command344 .as_ref()345 .trim_start_matches("sleep ")346 .parse::<f64>()347 .unwrap(),348 )349 }350}351352impl Executor for MockExecutor {353 fn run_command_and_measure(354 &self,355 command: &Command<'_>,356 _iteration: BenchmarkIteration,357 _command_failure_action: Option<CmdFailureAction>,358 _output_policy: &CommandOutputPolicy,359 ) -> Result<Measurement> {360 #[cfg(unix)]361 let exit_status = {362 use std::os::unix::process::ExitStatusExt;363 ExitStatus::from_raw(0)364 };365366 #[cfg(windows)]367 let exit_status = {368 use std::os::windows::process::ExitStatusExt;369 ExitStatus::from_raw(0)370 };371372 Ok(Measurement {373 time_wall_clock: Self::extract_time(command.get_command_line()),374 time_cpu: Time::zero(),375 time_user: Time::zero(),376 time_system: Time::zero(),377 memory_peak_resident: Some(Information::zero()),378 hardware_counters: Default::default(),379 exit_status,380 })381 }382383 fn calibrate(&mut self) -> Result<()> {384 Ok(())385 }386387 fn time_overhead(&self) -> Time {388 match &self.shell {389 None => Time::zero(),390 Some(shell) => Self::extract_time(shell),391 }392 }393}394395#[test]396fn test_mock_executor_extract_time() {397 assert_eq!(398 MockExecutor::extract_time("sleep 0.1"),399 Time::new::<second>(0.1)400 );401}