executor.rs
This file
Path
src/benchmark/executor.rs
374 lines · 12.0 KiB · Rust
Last changed by
Make memory units availableDavid Peterbefore adoptionf342e1f
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::{9 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,10};11use crate::output::progress_bar::get_progress_bar;12use crate::quantity::{second, Information, Quantity, Time};13use crate::timer::execute_and_measure;14use crate::util::randomized_environment_offset;1516use anyhow::{bail, Context, Result};1718#[derive(Clone, Copy)]19pub enum BenchmarkIteration {20 NonBenchmarkRun,21 Warmup(u64),22 Benchmark(u64),23}2425impl BenchmarkIteration {26 pub fn to_env_var_value(&self) -> Option<String> {27 match self {28 BenchmarkIteration::NonBenchmarkRun => None,29 BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)),30 BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)),31 }32 }33}3435pub trait Executor {36 /// Run the given command and measure the execution time37 fn run_command_and_measure(38 &self,39 command: &Command<'_>,40 iteration: BenchmarkIteration,41 command_failure_action: Option<CmdFailureAction>,42 output_policy: &CommandOutputPolicy,43 ) -> Result<Measurement>;4445 /// Perform a calibration of this executor. For example,46 /// when running commands through a shell, we need to47 /// measure the shell spawning time separately in order48 /// to subtract it from the full runtime later.49 fn calibrate(&mut self) -> Result<()>;5051 /// Return the time overhead for this executor when52 /// performing a measurement. This should return the time53 /// that is being used in addition to the actual runtime54 /// of the command.55 fn time_overhead(&self) -> Time;56}5758fn run_command_and_measure_common(59 mut command: std::process::Command,60 iteration: BenchmarkIteration,61 command_failure_action: CmdFailureAction,62 command_input_policy: &CommandInputPolicy,63 command_output_policy: &CommandOutputPolicy,64 command_name: &str,65) -> Result<Measurement> {66 let stdin = command_input_policy.get_stdin()?;67 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;68 command.stdin(stdin).stdout(stdout).stderr(stderr);6970 command.env(71 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",72 randomized_environment_offset::value(),73 );7475 if let Some(value) = iteration.to_env_var_value() {76 command.env("HYPERFINE_ITERATION", value);77 }7879 let measurement = execute_and_measure(command)80 .with_context(|| format!("Failed to run command '{command_name}'"))?;8182 if command_failure_action == CmdFailureAction::RaiseError && !measurement.exit_status.success()83 {84 let when = match iteration {85 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),86 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),87 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),88 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),89 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),90 };91 bail!(92 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \93 Alternatively, use the '--show-output' option to debug what went wrong.",94 cause=measurement.exit_status.code().map_or(95 "The process has been terminated by a signal".into(),96 |c| format!("Command terminated with non-zero exit code {c}")9798 let should_fail = match command_failure_action {99 CmdFailureAction::RaiseError => true,100 CmdFailureAction::IgnoreAllFailures => false,101 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {102 // Only fail if the exit code is not in the list of codes to ignore103 if let Some(exit_code) = extract_exit_code(result.exit_status) {104 !codes.contains(&exit_code)105 } else {106 // If we can't extract an exit code, treat it as a failure107 true108 }109 }110 };111112 if should_fail {113 let when = match iteration {114 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),115 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),116 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),117 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),118 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),119 };120 bail!(121 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \122 Alternatively, use the '--show-output' option to debug what went wrong.",123 cause=result.exit_status.code().map_or(124 "The process has been terminated by a signal".into(),125 |c| format!("Command terminated with non-zero exit code {c}")126127 ),128 );129 }130 }131132 Ok(measurement)133}134135pub struct RawExecutor<'a> {136 options: &'a Options,137}138139impl<'a> RawExecutor<'a> {140 pub fn new(options: &'a Options) -> Self {141 RawExecutor { options }142 }143}144145impl Executor for RawExecutor<'_> {146 fn run_command_and_measure(147 &self,148 command: &Command<'_>,149 iteration: BenchmarkIteration,150 command_failure_action: Option<CmdFailureAction>,151 output_policy: &CommandOutputPolicy,152 ) -> Result<Measurement> {153 run_command_and_measure_common(154 command.get_command()?,155 iteration,156 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),157 &self.options.command_input_policy,158 output_policy,159 &command.get_command_line(),160 )161 }162163 fn calibrate(&mut self) -> Result<()> {164 Ok(())165 }166167 fn time_overhead(&self) -> Time {168 Time::zero()169 }170}171172pub struct ShellExecutor<'a> {173 options: &'a Options,174 shell: &'a Shell,175 shell_spawning_time: Option<Measurement>,176}177178impl<'a> ShellExecutor<'a> {179 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {180 ShellExecutor {181 shell,182 options,183 shell_spawning_time: None,184 }185 }186}187188impl Executor for ShellExecutor<'_> {189 fn run_command_and_measure(190 &self,191 command: &Command<'_>,192 iteration: BenchmarkIteration,193 command_failure_action: Option<CmdFailureAction>,194 output_policy: &CommandOutputPolicy,195 ) -> Result<Measurement> {196 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");197 let mut command_builder = self.shell.command();198 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });199200 // Windows needs special treatment for its behavior on parsing cmd arguments201 if on_windows_cmd {202 #[cfg(windows)]203 command_builder.raw_arg(command.get_command_line());204 } else {205 command_builder.arg(command.get_command_line());206 }207208 let mut measurement = run_command_and_measure_common(209 command_builder,210 iteration,211 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),212 &self.options.command_input_policy,213 output_policy,214 &command.get_command_line(),215 )?;216217 // Subtract shell spawning time218 fn ensure_non_negative(time: Time) -> Time {219 if time < Time::zero() {220 Time::zero()221 } else {222 time223 }224 }225226 if let Some(ref spawning_time) = self.shell_spawning_time {227 measurement.time_wall_clock =228 ensure_non_negative(measurement.time_wall_clock - spawning_time.time_wall_clock);229 measurement.time_user =230 ensure_non_negative(measurement.time_user - spawning_time.time_user);231 measurement.time_system =232 ensure_non_negative(measurement.time_system - spawning_time.time_system);233 }234235 Ok(measurement)236 }237238 /// Measure the average shell spawning time239 fn calibrate(&mut self) -> Result<()> {240 const COUNT: u64 = 50;241 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {242 Some(get_progress_bar(243 COUNT,244 "Measuring shell spawning time",245 self.options.output_style,246 ))247 } else {248 None249 };250251 let mut measurements = Measurements::default();252253 for _ in 0..COUNT {254 // Just run the shell without any command255 let measurement = self.run_command_and_measure(256 &Command::new(None, ""),257 BenchmarkIteration::NonBenchmarkRun,258 None,259 &CommandOutputPolicy::Null,260 );261262 match measurement {263 Err(_) => {264 let shell_cmd = if cfg!(windows) {265 format!("{} /C \"\"", self.shell)266 } else {267 format!("{} -c \"\"", self.shell)268 };269270 bail!(271 "Could not measure shell execution time. Make sure you can run '{}'.",272 shell_cmd273 );274 }275 Ok(result) => {276 measurements.push(result);277 }278 }279280 if let Some(bar) = progress_bar.as_ref() {281 bar.inc(1)282 }283 }284285 if let Some(bar) = progress_bar.as_ref() {286 bar.finish_and_clear()287 }288289 self.shell_spawning_time = Some(Measurement {290 time_wall_clock: measurements.time_wall_clock_mean(),291 time_user: measurements.time_user_mean(),292 time_system: measurements.time_system_mean(),293 peak_memory_usage: measurements.peak_memory_usage_mean(),294 exit_status: ExitStatus::default(),295 });296297 Ok(())298 }299300 fn time_overhead(&self) -> Time {301 self.shell_spawning_time.as_ref().unwrap().time_wall_clock302 }303}304305#[derive(Clone)]306pub struct MockExecutor {307 shell: Option<String>,308}309310impl MockExecutor {311 pub fn new(shell: Option<String>) -> Self {312 MockExecutor { shell }313 }314315 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {316 assert!(sleep_command.as_ref().starts_with("sleep "));317 Time::new::<second>(318 sleep_command319 .as_ref()320 .trim_start_matches("sleep ")321 .parse::<f64>()322 .unwrap(),323 )324 }325}326327impl Executor for MockExecutor {328 fn run_command_and_measure(329 &self,330 command: &Command<'_>,331 _iteration: BenchmarkIteration,332 _command_failure_action: Option<CmdFailureAction>,333 _output_policy: &CommandOutputPolicy,334 ) -> Result<Measurement> {335 #[cfg(unix)]336 let exit_status = {337 use std::os::unix::process::ExitStatusExt;338 ExitStatus::from_raw(0)339 };340341 #[cfg(windows)]342 let exit_status = {343 use std::os::windows::process::ExitStatusExt;344 ExitStatus::from_raw(0)345 };346347 Ok(Measurement {348 time_wall_clock: Self::extract_time(command.get_command_line()),349 time_user: Time::zero(),350 time_system: Time::zero(),351 peak_memory_usage: Information::zero(),352 exit_status,353 })354 }355356 fn calibrate(&mut self) -> Result<()> {357 Ok(())358 }359360 fn time_overhead(&self) -> Time {361 match &self.shell {362 None => Time::zero(),363 Some(shell) => Self::extract_time(shell),364 }365 }366}367368#[test]369fn test_mock_executor_extract_time() {370 assert_eq!(371 MockExecutor::extract_time("sleep 0.1"),372 Time::new::<second>(0.1)373 );374}