executor.rs
This file
Path
src/benchmark/executor.rs
368 lines · 11.3 KiB · Rust
Last changed by
Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
History of this fileTake it
The walk stopped after 200 commits: lines older than 27ec9e2 point at it.
fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
line 1why, one step back1#[cfg(windows)] bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 2why, one step back2use std::os::windows::process::CommandExt;Add the rest of the suggestions from code reviewSteve Neasebefore adoptiond32b90e
line 3why, one step back3use std::process::ExitStatus;use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 4–5why, one step back45use crate::command::Command;ran cargo fmtSteve Neasebefore adoption0e3bad1
lines 6–8why, one step back6use crate::options::{7 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,8};use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 9–18why, one step back9use crate::output::progress_bar::get_progress_bar;10use crate::timer::{execute_and_measure, TimerResult};11use crate::util::randomized_environment_offset;12use crate::util::units::Second;1314use super::timing_result::TimingResult;1516use anyhow::{bail, Context, Result};17use statistical::mean;18Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 19–34why, one step back19pub 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}34use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 35–39why, one step back35pub trait Executor {36 /// Run the given command and measure the execution time37 fn run_command_and_measure(38 &self,39 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 40why, one step back40 iteration: BenchmarkIteration,use set and settrueBenjamin Rombautbefore adoption27ec9e2
line 41why, one step back41 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 42why, one step back42 output_policy: &CommandOutputPolicy,use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 43–59why, one step back43 ) -> Result<(TimingResult, ExitStatus)>;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) -> Second;56}5758fn run_command_and_measure_common(59 mut command: std::process::Command,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 60why, one step back60 iteration: BenchmarkIteration,use set and settrueBenjamin Rombautbefore adoption27ec9e2
line 61why, one step back61 command_failure_action: CmdFailureAction,Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 62why, one step back62 command_input_policy: &CommandInputPolicy,use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 63–65why, one step back63 command_output_policy: &CommandOutputPolicy,64 command_name: &str,65) -> Result<TimerResult> {Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 66why, one step back66 let stdin = command_input_policy.get_stdin()?;Change order of input/oututDavid Peterbefore adoptione88fa27
line 67why, one step back67 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 68why, one step back68 command.stdin(stdin).stdout(stdout).stderr(stderr);use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 69–74why, one step back6970 command.env(71 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",72 randomized_environment_offset::value(),73 );74Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 75–78why, one step back75 if let Some(value) = iteration.to_env_var_value() {76 command.env("HYPERFINE_ITERATION", value);77 }78use set and settrueBenjamin Rombautbefore adoption27ec9e2
line 79why, one step back79 let result = execute_and_measure(command)style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 80why, one step back80 .with_context(|| format!("Failed to run command '{command_name}'"))?;use set and settrueBenjamin Rombautbefore adoption27ec9e2
line 81why, one step back81Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 82–96why, one step back82 if !result.status.success() {83 use crate::util::exit_code::extract_exit_code;8485 let should_fail = match command_failure_action {86 CmdFailureAction::RaiseError => true,87 CmdFailureAction::IgnoreAllFailures => false,88 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {89 // Only fail if the exit code is not in the list of codes to ignore90 if let Some(exit_code) = extract_exit_code(result.status) {91 !codes.contains(&exit_code)92 } else {93 // If we can't extract an exit code, treat it as a failure94 true95 }96 }Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 97–98why, one step back97 };98Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 99–116why, one step back99 if should_fail {100 let when = match iteration {101 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),102 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),103 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),104 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),105 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),106 };107 bail!(108 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \109 Alternatively, use the '--show-output' option to debug what went wrong.",110 cause=result.status.code().map_or(111 "The process has been terminated by a signal".into(),112 |c| format!("Command terminated with non-zero exit code {c}")113114 ),115 );116 }use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 117–131why, one step back117 }118119 Ok(result)120}121122pub struct RawExecutor<'a> {123 options: &'a Options,124}125126impl<'a> RawExecutor<'a> {127 pub fn new(options: &'a Options) -> Self {128 RawExecutor { options }129 }130}131apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 132why, one step back132impl Executor for RawExecutor<'_> {use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 133–135why, one step back133 fn run_command_and_measure(134 &self,135 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 136why, one step back136 iteration: BenchmarkIteration,use set and settrueBenjamin Rombautbefore adoption27ec9e2
line 137why, one step back137 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 138why, one step back138 output_policy: &CommandOutputPolicy,use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 139–141why, one step back139 ) -> Result<(TimingResult, ExitStatus)> {140 let result = run_command_and_measure_common(141 command.get_command()?,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 142why, one step back142 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 143why, one step back143 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 144why, one step back144 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 145why, one step back145 output_policy,use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 146–153why, one step back146 &command.get_command_line(),147 )?;148149 Ok((150 TimingResult {151 time_real: result.time_real,152 time_user: result.time_user,153 time_system: result.time_system,Initial work on tracking memory usageDavid Peterbefore adoption6556b2b
line 154why, one step back154 memory_usage_byte: result.memory_usage_byte,use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 155–184why, one step back155 },156 result.status,157 ))158 }159160 fn calibrate(&mut self) -> Result<()> {161 Ok(())162 }163164 fn time_overhead(&self) -> Second {165 0.0166 }167}168169pub struct ShellExecutor<'a> {170 options: &'a Options,171 shell: &'a Shell,172 shell_spawning_time: Option<TimingResult>,173}174175impl<'a> ShellExecutor<'a> {176 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {177 ShellExecutor {178 shell,179 options,180 shell_spawning_time: None,181 }182 }183}184apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 185why, one step back185impl Executor for ShellExecutor<'_> {use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 186–188why, one step back186 fn run_command_and_measure(187 &self,188 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 189why, one step back189 iteration: BenchmarkIteration,use set and settrueBenjamin Rombautbefore adoption27ec9e2
line 190why, one step back190 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 191why, one step back191 output_policy: &CommandOutputPolicy,use set and settrueBenjamin Rombautbefore adoption27ec9e2
line 192why, one step back192 ) -> Result<(TimingResult, ExitStatus)> { bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 193why, one step back193 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");use set and settrueBenjamin Rombautbefore adoption27ec9e2
line 194why, one step back194 let mut command_builder = self.shell.command();fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
line 195why, one step back195 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" }); bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 196why, one step back196fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 197–198why, one step back197 // Windows needs special treatment for its behavior on parsing cmd arguments198 if on_windows_cmd {cfg: adding more pre-processing for windows-only parserPedro Witzelbefore adoptionae9b0bb
line 199why, one step back199 #[cfg(windows)]fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 200–203why, one step back200 command_builder.raw_arg(command.get_command_line());201 } else {202 command_builder.arg(command.get_command_line());203 }use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 204–206why, one step back204205 let mut result = run_command_and_measure_common(206 command_builder,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 207why, one step back207 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 208why, one step back208 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 209why, one step back209 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 210why, one step back210 output_policy,use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 211–225why, one step back211 &command.get_command_line(),212 )?;213214 // Subtract shell spawning time215 if let Some(spawning_time) = self.shell_spawning_time {216 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);217 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);218 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);219 }220221 Ok((222 TimingResult {223 time_real: result.time_real,224 time_user: result.time_user,225 time_system: result.time_system,Initial work on tracking memory usageDavid Peterbefore adoption6556b2b
line 226why, one step back226 memory_usage_byte: result.memory_usage_byte,use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 227–250why, one step back227 },228 result.status,229 ))230 }231232 /// Measure the average shell spawning time233 fn calibrate(&mut self) -> Result<()> {234 const COUNT: u64 = 50;235 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {236 Some(get_progress_bar(237 COUNT,238 "Measuring shell spawning time",239 self.options.output_style,240 ))241 } else {242 None243 };244245 let mut times_real: Vec<Second> = vec![];246 let mut times_user: Vec<Second> = vec![];247 let mut times_system: Vec<Second> = vec![];248249 for _ in 0..COUNT {250 // Just run the shell without any commandAdd iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 251–254why, one step back251 let res = self.run_command_and_measure(252 &Command::new(None, ""),253 BenchmarkIteration::NonBenchmarkRun,254 None,Multiple output policiesDavid Peterbefore adoption99d24b7
line 255why, one step back255 &CommandOutputPolicy::Null,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 256why, one step back256 );use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 257–290why, one step back257258 match res {259 Err(_) => {260 let shell_cmd = if cfg!(windows) {261 format!("{} /C \"\"", self.shell)262 } else {263 format!("{} -c \"\"", self.shell)264 };265266 bail!(267 "Could not measure shell execution time. Make sure you can run '{}'.",268 shell_cmd269 );270 }271 Ok((r, _)) => {272 times_real.push(r.time_real);273 times_user.push(r.time_user);274 times_system.push(r.time_system);275 }276 }277278 if let Some(bar) = progress_bar.as_ref() {279 bar.inc(1)280 }281 }282283 if let Some(bar) = progress_bar.as_ref() {284 bar.finish_and_clear()285 }286287 self.shell_spawning_time = Some(TimingResult {288 time_real: mean(×_real),289 time_user: mean(×_user),290 time_system: mean(×_system),Initial work on tracking memory usageDavid Peterbefore adoption6556b2b
line 291why, one step back291 memory_usage_byte: 0,use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 292–325why, one step back292 });293294 Ok(())295 }296297 fn time_overhead(&self) -> Second {298 self.shell_spawning_time.unwrap().time_real299 }300}301302#[derive(Clone)]303pub struct MockExecutor {304 shell: Option<String>,305}306307impl MockExecutor {308 pub fn new(shell: Option<String>) -> Self {309 MockExecutor { shell }310 }311312 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {313 assert!(sleep_command.as_ref().starts_with("sleep "));314 sleep_command315 .as_ref()316 .trim_start_matches("sleep ")317 .parse::<Second>()318 .unwrap()319 }320}321322impl Executor for MockExecutor {323 fn run_command_and_measure(324 &self,325 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 326why, one step back326 _iteration: BenchmarkIteration,use set and settrueBenjamin Rombautbefore adoption27ec9e2
line 327why, one step back327 _command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 328why, one step back328 _output_policy: &CommandOutputPolicy,use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 329–346why, one step back329 ) -> Result<(TimingResult, ExitStatus)> {330 #[cfg(unix)]331 let status = {332 use std::os::unix::process::ExitStatusExt;333 ExitStatus::from_raw(0)334 };335336 #[cfg(windows)]337 let status = {338 use std::os::windows::process::ExitStatusExt;339 ExitStatus::from_raw(0)340 };341342 Ok((343 TimingResult {344 time_real: Self::extract_time(command.get_command_line()),345 time_user: 0.0,346 time_system: 0.0,Initial work on tracking memory usageDavid Peterbefore adoption6556b2b
line 347why, one step back347 memory_usage_byte: 0,use set and settrueBenjamin Rombautbefore adoption27ec9e2
lines 348–368why, one step back348 },349 status,350 ))351 }352353 fn calibrate(&mut self) -> Result<()> {354 Ok(())355 }356357 fn time_overhead(&self) -> Second {358 match &self.shell {359 None => 0.0,360 Some(shell) => Self::extract_time(shell),361 }362 }363}364365#[test]366fn test_mock_executor_extract_time() {367 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);368}