executor.rs
This file
Path
src/benchmark/executor.rs
369 lines · 11.6 KiB · Rust
Last changed by
Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
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, Time, Zero};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 collect_hardware_counters: bool,66) -> Result<Measurement> {67 let stdin = command_input_policy.get_stdin()?;68 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;69 command.stdin(stdin).stdout(stdout).stderr(stderr);7071 command.env(72 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",73 randomized_environment_offset::value(),74 );7576 if let Some(value) = iteration.to_env_var_value() {77 command.env("HYPERFINE_ITERATION", value);78 }7980 let measurement = execute_and_measure(command, collect_hardware_counters)81 .with_context(|| format!("Failed to run command '{command_name}'"))?;8283 if !measurement.exit_status.success() {84 use crate::util::exit_code::extract_exit_code;8586 let should_fail = match command_failure_action {87 CmdFailureAction::RaiseError => true,88 CmdFailureAction::IgnoreAllFailures => false,89 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {90 // Only fail if the exit code is not in the list of codes to ignore91 if let Some(exit_code) = extract_exit_code(measurement.exit_status) {92 !codes.contains(&exit_code)93 } else {94 // If we can't extract an exit code, treat it as a failure95 true96 }97 }98 };99100 if should_fail {101 let when = match iteration {102 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),103 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),104 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),105 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),106 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),107 };108 bail!(109 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \110 Alternatively, use the '--show-output' option to debug what went wrong.",111 cause=measurement.exit_status.code().map_or(112 "The process has been terminated by a signal".into(),113 |c| format!("Command terminated with non-zero exit code {c}")114115 ),116 );117 }118 }119120 Ok(measurement)121}122123pub struct RawExecutor<'a> {124 options: &'a Options,125}126127impl<'a> RawExecutor<'a> {128 pub fn new(options: &'a Options) -> Self {129 RawExecutor { options }130 }131}132133impl Executor for RawExecutor<'_> {134 fn run_command_and_measure(135 &self,136 command: &Command<'_>,137 iteration: BenchmarkIteration,138 command_failure_action: Option<CmdFailureAction>,139 output_policy: &CommandOutputPolicy,140 ) -> Result<Measurement> {141 run_command_and_measure_common(142 command.get_command()?,143 iteration,144 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),145 &self.options.command_input_policy,146 output_policy,147 &command.get_command_line(),148 matches!(iteration, BenchmarkIteration::Benchmark(_)),149 )150 }151152 fn calibrate(&mut self) -> Result<()> {153 Ok(())154 }155156 fn time_overhead(&self) -> Time {157 Time::zero()158 }159}160161pub struct ShellExecutor<'a> {162 options: &'a Options,163 shell: &'a Shell,164 shell_spawning_time: Option<Measurement>,165}166167impl<'a> ShellExecutor<'a> {168 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {169 ShellExecutor {170 shell,171 options,172 shell_spawning_time: None,173 }174 }175}176177impl Executor for ShellExecutor<'_> {178 fn run_command_and_measure(179 &self,180 command: &Command<'_>,181 iteration: BenchmarkIteration,182 command_failure_action: Option<CmdFailureAction>,183 output_policy: &CommandOutputPolicy,184 ) -> Result<Measurement> {185 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");186 let mut command_builder = self.shell.command();187 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });188189 // Windows needs special treatment for its behavior on parsing cmd arguments190 if on_windows_cmd {191 #[cfg(windows)]192 command_builder.raw_arg(command.get_command_line());193 } else {194 command_builder.arg(command.get_command_line());195 }196197 let mut measurement = run_command_and_measure_common(198 command_builder,199 iteration,200 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),201 &self.options.command_input_policy,202 output_policy,203 &command.get_command_line(),204 false,205 )?;206207 // Subtract shell spawning time208 fn ensure_non_negative(time: Time) -> Time {209 if time < Time::zero() {210 Time::zero()211 } else {212 time213 }214 }215216 if let Some(ref spawning_time) = self.shell_spawning_time {217 measurement.time_wall_clock =218 ensure_non_negative(measurement.time_wall_clock - spawning_time.time_wall_clock);219 measurement.time_user =220 ensure_non_negative(measurement.time_user - spawning_time.time_user);221 measurement.time_system =222 ensure_non_negative(measurement.time_system - spawning_time.time_system);223 measurement.time_cpu = measurement.time_user + measurement.time_system;224 }225226 Ok(measurement)227 }228229 /// Measure the average shell spawning time230 fn calibrate(&mut self) -> Result<()> {231 const COUNT: u64 = 50;232 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {233 Some(get_progress_bar(234 COUNT,235 "Measuring shell spawning time",236 self.options.output_style,237 ))238 } else {239 None240 };241242 let mut measurements = Measurements::default();243244 for _ in 0..COUNT {245 // Just run the shell without any command246 let measurement = self.run_command_and_measure(247 &Command::new(None, ""),248 BenchmarkIteration::NonBenchmarkRun,249 None,250 &CommandOutputPolicy::Null,251 );252253 match measurement {254 Err(_) => {255 let shell_cmd = if cfg!(windows) {256 format!("{} /C \"\"", self.shell)257 } else {258 format!("{} -c \"\"", self.shell)259 };260261 bail!(262 "Could not measure shell execution time. Make sure you can run '{}'.",263 shell_cmd264 );265 }266 Ok(result) => {267 measurements.push(result);268 }269 }270271 if let Some(bar) = progress_bar.as_ref() {272 bar.inc(1)273 }274 }275276 if let Some(bar) = progress_bar.as_ref() {277 bar.finish_and_clear()278 }279280 self.shell_spawning_time = Some(Measurement {281 time_wall_clock: measurements.time_wall_clock_mean(),282 time_cpu: measurements.time_user_mean() + measurements.time_system_mean(),283 time_user: measurements.time_user_mean(),284 time_system: measurements.time_system_mean(),285 memory_peak_resident: None,286 hardware_counters: Default::default(),287 exit_status: ExitStatus::default(),288 });289290 Ok(())291 }292293 fn time_overhead(&self) -> Time {294 self.shell_spawning_time.as_ref().unwrap().time_wall_clock295 }296}297298#[derive(Clone)]299pub struct MockExecutor {300 shell: Option<String>,301}302303impl MockExecutor {304 pub fn new(shell: Option<String>) -> Self {305 MockExecutor { shell }306 }307308 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {309 assert!(sleep_command.as_ref().starts_with("sleep "));310 Time::new::<second>(311 sleep_command312 .as_ref()313 .trim_start_matches("sleep ")314 .parse::<f64>()315 .unwrap(),316 )317 }318}319320impl Executor for MockExecutor {321 fn run_command_and_measure(322 &self,323 command: &Command<'_>,324 _iteration: BenchmarkIteration,325 _command_failure_action: Option<CmdFailureAction>,326 _output_policy: &CommandOutputPolicy,327 ) -> Result<Measurement> {328 #[cfg(unix)]329 let exit_status = {330 use std::os::unix::process::ExitStatusExt;331 ExitStatus::from_raw(0)332 };333334 #[cfg(windows)]335 let exit_status = {336 use std::os::windows::process::ExitStatusExt;337 ExitStatus::from_raw(0)338 };339340 Ok(Measurement {341 time_wall_clock: Self::extract_time(command.get_command_line()),342 time_cpu: Time::zero(),343 time_user: Time::zero(),344 time_system: Time::zero(),345 memory_peak_resident: Some(Information::zero()),346 hardware_counters: Default::default(),347 exit_status,348 })349 }350351 fn calibrate(&mut self) -> Result<()> {352 Ok(())353 }354355 fn time_overhead(&self) -> Time {356 match &self.shell {357 None => Time::zero(),358 Some(shell) => Self::extract_time(shell),359 }360 }361}362363#[test]364fn test_mock_executor_extract_time() {365 assert_eq!(366 MockExecutor::extract_time("sleep 0.1"),367 Time::new::<second>(0.1)368 );369}