executor.rs
This file
Path
src/benchmark/executor.rs
376 lines · 12.1 KiB · Rust
Last changed by
RefactoringDavid Peterbefore adoption71365c2
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::Information;13use crate::quantity::InformationQuantity;14use crate::quantity::{Time, TimeQuantity};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 measurement = execute_and_measure(command)82 .with_context(|| format!("Failed to run command '{command_name}'"))?;8384 if command_failure_action == CmdFailureAction::RaiseError && !measurement.exit_status.success()85 {86 let when = match iteration {87 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),88 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),89 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),90 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),91 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),92 };93 bail!(94 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \95 Alternatively, use the '--show-output' option to debug what went wrong.",96 cause=measurement.exit_status.code().map_or(97 "The process has been terminated by a signal".into(),98 |c| format!("Command terminated with non-zero exit code {c}")99100 let should_fail = match command_failure_action {101 CmdFailureAction::RaiseError => true,102 CmdFailureAction::IgnoreAllFailures => false,103 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {104 // Only fail if the exit code is not in the list of codes to ignore105 if let Some(exit_code) = extract_exit_code(result.exit_status) {106 !codes.contains(&exit_code)107 } else {108 // If we can't extract an exit code, treat it as a failure109 true110 }111 }112 };113114 if should_fail {115 let when = match iteration {116 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),117 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),118 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),119 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),120 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),121 };122 bail!(123 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \124 Alternatively, use the '--show-output' option to debug what went wrong.",125 cause=result.exit_status.code().map_or(126 "The process has been terminated by a signal".into(),127 |c| format!("Command terminated with non-zero exit code {c}")128129 ),130 );131 }132 }133134 Ok(measurement)135}136137pub struct RawExecutor<'a> {138 options: &'a Options,139}140141impl<'a> RawExecutor<'a> {142 pub fn new(options: &'a Options) -> Self {143 RawExecutor { options }144 }145}146147impl Executor for RawExecutor<'_> {148 fn run_command_and_measure(149 &self,150 command: &Command<'_>,151 iteration: BenchmarkIteration,152 command_failure_action: Option<CmdFailureAction>,153 output_policy: &CommandOutputPolicy,154 ) -> Result<Measurement> {155 run_command_and_measure_common(156 command.get_command()?,157 iteration,158 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),159 &self.options.command_input_policy,160 output_policy,161 &command.get_command_line(),162 )163 }164165 fn calibrate(&mut self) -> Result<()> {166 Ok(())167 }168169 fn time_overhead(&self) -> Time {170 Time::zero()171 }172}173174pub struct ShellExecutor<'a> {175 options: &'a Options,176 shell: &'a Shell,177 shell_spawning_time: Option<Measurement>,178}179180impl<'a> ShellExecutor<'a> {181 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {182 ShellExecutor {183 shell,184 options,185 shell_spawning_time: None,186 }187 }188}189190impl Executor for ShellExecutor<'_> {191 fn run_command_and_measure(192 &self,193 command: &Command<'_>,194 iteration: BenchmarkIteration,195 command_failure_action: Option<CmdFailureAction>,196 output_policy: &CommandOutputPolicy,197 ) -> Result<Measurement> {198 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");199 let mut command_builder = self.shell.command();200 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });201202 // Windows needs special treatment for its behavior on parsing cmd arguments203 if on_windows_cmd {204 #[cfg(windows)]205 command_builder.raw_arg(command.get_command_line());206 } else {207 command_builder.arg(command.get_command_line());208 }209210 let mut measurement = run_command_and_measure_common(211 command_builder,212 iteration,213 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),214 &self.options.command_input_policy,215 output_policy,216 &command.get_command_line(),217 )?;218219 // Subtract shell spawning time220 fn ensure_non_negative(time: Time) -> Time {221 if time < Time::zero() {222 Time::zero()223 } else {224 time225 }226 }227228 if let Some(ref spawning_time) = self.shell_spawning_time {229 measurement.time_wall_clock =230 ensure_non_negative(measurement.time_wall_clock - spawning_time.time_wall_clock);231 measurement.time_user =232 ensure_non_negative(measurement.time_user - spawning_time.time_user);233 measurement.time_system =234 ensure_non_negative(measurement.time_system - spawning_time.time_system);235 }236237 Ok(measurement)238 }239240 /// Measure the average shell spawning time241 fn calibrate(&mut self) -> Result<()> {242 const COUNT: u64 = 50;243 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {244 Some(get_progress_bar(245 COUNT,246 "Measuring shell spawning time",247 self.options.output_style,248 ))249 } else {250 None251 };252253 let mut measurements = Measurements::default();254255 for _ in 0..COUNT {256 // Just run the shell without any command257 let measurement = self.run_command_and_measure(258 &Command::new(None, ""),259 BenchmarkIteration::NonBenchmarkRun,260 None,261 &CommandOutputPolicy::Null,262 );263264 match measurement {265 Err(_) => {266 let shell_cmd = if cfg!(windows) {267 format!("{} /C \"\"", self.shell)268 } else {269 format!("{} -c \"\"", self.shell)270 };271272 bail!(273 "Could not measure shell execution time. Make sure you can run '{}'.",274 shell_cmd275 );276 }277 Ok(result) => {278 measurements.push(result);279 }280 }281282 if let Some(bar) = progress_bar.as_ref() {283 bar.inc(1)284 }285 }286287 if let Some(bar) = progress_bar.as_ref() {288 bar.finish_and_clear()289 }290291 self.shell_spawning_time = Some(Measurement {292 time_wall_clock: measurements.time_wall_clock_mean(),293 time_user: measurements.time_user_mean(),294 time_system: measurements.time_system_mean(),295 peak_memory_usage: measurements.peak_memory_usage_mean(),296 exit_status: ExitStatus::default(),297 });298299 Ok(())300 }301302 fn time_overhead(&self) -> Time {303 self.shell_spawning_time.as_ref().unwrap().time_wall_clock304 }305}306307#[derive(Clone)]308pub struct MockExecutor {309 shell: Option<String>,310}311312impl MockExecutor {313 pub fn new(shell: Option<String>) -> Self {314 MockExecutor { shell }315 }316317 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {318 assert!(sleep_command.as_ref().starts_with("sleep "));319 Time::from_seconds(320 sleep_command321 .as_ref()322 .trim_start_matches("sleep ")323 .parse::<f64>()324 .unwrap(),325 )326 }327}328329impl Executor for MockExecutor {330 fn run_command_and_measure(331 &self,332 command: &Command<'_>,333 _iteration: BenchmarkIteration,334 _command_failure_action: Option<CmdFailureAction>,335 _output_policy: &CommandOutputPolicy,336 ) -> Result<Measurement> {337 #[cfg(unix)]338 let exit_status = {339 use std::os::unix::process::ExitStatusExt;340 ExitStatus::from_raw(0)341 };342343 #[cfg(windows)]344 let exit_status = {345 use std::os::windows::process::ExitStatusExt;346 ExitStatus::from_raw(0)347 };348349 Ok(Measurement {350 time_wall_clock: Self::extract_time(command.get_command_line()),351 time_user: Time::zero(),352 time_system: Time::zero(),353 peak_memory_usage: Information::from_bytes(0),354 exit_status,355 })356 }357358 fn calibrate(&mut self) -> Result<()> {359 Ok(())360 }361362 fn time_overhead(&self) -> Time {363 match &self.shell {364 None => Time::zero(),365 Some(shell) => Self::extract_time(shell),366 }367 }368}369370#[test]371fn test_mock_executor_extract_time() {372 assert_eq!(373 MockExecutor::extract_time("sleep 0.1"),374 Time::from_seconds(0.1)375 );376}