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
The walk stopped after 200 commits: lines older than acf156e 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;ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 3–4why, one step back3use std::process::ExitStatus;4Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 5–6why, one step back5use crate::benchmark::measurement::Measurement;6use crate::benchmark::measurement::Measurements;ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 7–11why, one step back7use crate::command::Command;8use crate::options::{9 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,10};11use crate::output::progress_bar::get_progress_bar;Move quantity moduleDavid Peterbefore adoptionbe66a66
lines 12–14why, one step back12use crate::quantity::Information;13use crate::quantity::InformationQuantity;14use crate::quantity::{Time, TimeQuantity};Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 15why, one step back15use crate::timer::execute_and_measure;ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 16–19why, one step back16use crate::util::randomized_environment_offset;1718use anyhow::{bail, Context, Result};19Merge pull request #807 from willcl-ark/expose-run-varDavid Peterbefore adoption30a2b61
line 20why, one step back20#[derive(Clone, Copy)]Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 21–36why, one step back21pub 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}36ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 37–41why, one step back37pub trait Executor {38 /// Run the given command and measure the execution time39 fn run_command_and_measure(40 &self,41 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 42why, one step back42 iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 43why, one step back43 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 44why, one step back44 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 45why, one step back45 ) -> Result<Measurement>;ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 46–56why, one step back4647 /// 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.Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 57why, one step back57 fn time_overhead(&self) -> Time;ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 58–61why, one step back58}5960fn run_command_and_measure_common(61 mut command: std::process::Command,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 62why, one step back62 iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 63–66why, one step back63 command_failure_action: CmdFailureAction,64 command_input_policy: &CommandInputPolicy,65 command_output_policy: &CommandOutputPolicy,66 command_name: &str,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 67why, one step back67) -> Result<Measurement> {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 68–76why, one step back68 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 );76Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 77–80why, one step back77 if let Some(value) = iteration.to_env_var_value() {78 command.env("HYPERFINE_ITERATION", value);79 }80RefactoringDavid Peterbefore adoption71365c2
line 81why, one step back81 let measurement = execute_and_measure(command)style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 82why, one step back82 .with_context(|| format!("Failed to run command '{command_name}'"))?;ran cargo fmtHumble Penguinbefore adoptionacf156e
line 83why, one step back83RefactoringDavid Peterbefore adoption71365c2
lines 84–85why, one step back84 if command_failure_action == CmdFailureAction::RaiseError && !measurement.exit_status.success()85 {Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 86–95why, one step back86 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.",RefactoringDavid Peterbefore adoption71365c2
line 96why, one step back96 cause=measurement.exit_status.code().map_or(Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 97–98why, one step back97 "The process has been terminated by a signal".into(),98 |c| format!("Command terminated with non-zero exit code {c}")Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 99–104why, one step back99100 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 ignoreMerge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 105why, one step back105 if let Some(exit_code) = extract_exit_code(result.exit_status) {Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 106–111why, one step back106 !codes.contains(&exit_code)107 } else {108 // If we can't extract an exit code, treat it as a failure109 true110 }111 }Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 112–113why, one step back112 };113Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 114–124why, one step back114 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.",Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 125why, one step back125 cause=result.exit_status.code().map_or(Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 126–131why, one step back126 "The process has been terminated by a signal".into(),127 |c| format!("Command terminated with non-zero exit code {c}")128129 ),130 );131 }ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 132–133why, one step back132 }133RefactoringDavid Peterbefore adoption71365c2
line 134why, one step back134 Ok(measurement)ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 135–146why, one step back135}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}146apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 147why, one step back147impl Executor for RawExecutor<'_> {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 148–150why, one step back148 fn run_command_and_measure(149 &self,150 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 151why, one step back151 iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 152why, one step back152 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 153why, one step back153 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 154why, one step back154 ) -> Result<Measurement> {RefactoringDavid Peterbefore adoption71365c2
line 155why, one step back155 run_command_and_measure_common(ran cargo fmtHumble Penguinbefore adoptionacf156e
line 156why, one step back156 command.get_command()?,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 157why, one step back157 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 158why, one step back158 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),ran cargo fmtHumble Penguinbefore adoptionacf156e
line 159why, one step back159 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 160why, one step back160 output_policy,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 161why, one step back161 &command.get_command_line(),RefactoringDavid Peterbefore adoption71365c2
line 162why, one step back162 )ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 163–168why, one step back163 }164165 fn calibrate(&mut self) -> Result<()> {166 Ok(())167 }168Use uomDavid Peterbefore adoption641451a
lines 169–170why, one step back169 fn time_overhead(&self) -> Time {170 Time::zero()ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 171–176why, one step back171 }172}173174pub struct ShellExecutor<'a> {175 options: &'a Options,176 shell: &'a Shell,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 177why, one step back177 shell_spawning_time: Option<Measurement>,ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 178–189why, one step back178}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}189apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 190why, one step back190impl Executor for ShellExecutor<'_> {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 191–193why, one step back191 fn run_command_and_measure(192 &self,193 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 194why, one step back194 iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 195why, one step back195 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 196why, one step back196 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 197why, one step back197 ) -> Result<Measurement> { bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 198why, one step back198 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");ran cargo fmtHumble Penguinbefore adoptionacf156e
line 199why, one step back199 let mut command_builder = self.shell.command();fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
line 200why, one step back200 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" }); bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 201why, one step back201fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 202–203why, one step back202 // Windows needs special treatment for its behavior on parsing cmd arguments203 if on_windows_cmd {cfg: adding more pre-processing for windows-only parserPedro Witzelbefore adoptionae9b0bb
line 204why, one step back204 #[cfg(windows)]fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 205–208why, one step back205 command_builder.raw_arg(command.get_command_line());206 } else {207 command_builder.arg(command.get_command_line());208 }ran cargo fmtHumble Penguinbefore adoptionacf156e
line 209why, one step back209RefactoringDavid Peterbefore adoption71365c2
line 210why, one step back210 let mut measurement = run_command_and_measure_common(ran cargo fmtHumble Penguinbefore adoptionacf156e
line 211why, one step back211 command_builder,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 212why, one step back212 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 213why, one step back213 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),ran cargo fmtHumble Penguinbefore adoptionacf156e
line 214why, one step back214 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 215why, one step back215 output_policy,ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 216–219why, one step back216 &command.get_command_line(),217 )?;218219 // Subtract shell spawning timeUse uomDavid Peterbefore adoption641451a
lines 220–222why, one step back220 fn ensure_non_negative(time: Time) -> Time {221 if time < Time::zero() {222 Time::zero()Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299
lines 223–227why, one step back223 } else {224 time225 }226 }227Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 228why, one step back228 if let Some(ref spawning_time) = self.shell_spawning_time {RefactoringDavid Peterbefore adoption71365c2
lines 229–234why, one step back229 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);ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 235–236why, one step back235 }236RefactoringDavid Peterbefore adoption71365c2
line 237why, one step back237 Ok(measurement)ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 238–252why, one step back238 }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 };252Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 253why, one step back253 let mut measurements = Measurements::default();ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 254–256why, one step back254255 for _ in 0..COUNT {256 // Just run the shell without any commandUnify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 257why, one step back257 let measurement = self.run_command_and_measure(Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 258–260why, one step back258 &Command::new(None, ""),259 BenchmarkIteration::NonBenchmarkRun,260 None,Multiple output policiesDavid Peterbefore adoption99d24b7
line 261why, one step back261 &CommandOutputPolicy::Null,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 262why, one step back262 );ran cargo fmtHumble Penguinbefore adoptionacf156e
line 263why, one step back263Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 264why, one step back264 match measurement {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 265–276why, one step back265 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 }Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 277–278why, one step back277 Ok(result) => {278 measurements.push(result);ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 279–290why, one step back279 }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 }290Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 291–296why, one step back291 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(),ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 297–301why, one step back297 });298299 Ok(())300 }301Use uomDavid Peterbefore adoption641451a
line 302why, one step back302 fn time_overhead(&self) -> Time {Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 303why, one step back303 self.shell_spawning_time.as_ref().unwrap().time_wall_clockran cargo fmtHumble Penguinbefore adoptionacf156e
lines 304–316why, one step back304 }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 }316Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 317why, one step back317 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {ran cargo fmtHumble Penguinbefore adoptionacf156e
line 318why, one step back318 assert!(sleep_command.as_ref().starts_with("sleep "));Use uomDavid Peterbefore adoption641451a
line 319why, one step back319 Time::from_seconds(Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
lines 320–325why, one step back320 sleep_command321 .as_ref()322 .trim_start_matches("sleep ")323 .parse::<f64>()324 .unwrap(),325 )ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 326–332why, one step back326 }327}328329impl Executor for MockExecutor {330 fn run_command_and_measure(331 &self,332 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 333why, one step back333 _iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 334why, one step back334 _command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 335why, one step back335 _output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 336why, one step back336 ) -> Result<Measurement> {ran cargo fmtHumble Penguinbefore adoptionacf156e
line 337why, one step back337 #[cfg(unix)]Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 338why, one step back338 let exit_status = {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 339–343why, one step back339 use std::os::unix::process::ExitStatusExt;340 ExitStatus::from_raw(0)341 };342343 #[cfg(windows)]Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 344why, one step back344 let exit_status = {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 345–348why, one step back345 use std::os::windows::process::ExitStatusExt;346 ExitStatus::from_raw(0)347 };348Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 349–350why, one step back349 Ok(Measurement {350 time_wall_clock: Self::extract_time(command.get_command_line()),Use uomDavid Peterbefore adoption641451a
lines 351–353why, one step back351 time_user: Time::zero(),352 time_system: Time::zero(),353 peak_memory_usage: Information::from_bytes(0),Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 354–355why, one step back354 exit_status,355 })ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 356–361why, one step back356 }357358 fn calibrate(&mut self) -> Result<()> {359 Ok(())360 }361Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 362why, one step back362 fn time_overhead(&self) -> Time {ran cargo fmtHumble Penguinbefore adoptionacf156e
line 363why, one step back363 match &self.shell {Use uomDavid Peterbefore adoption641451a
line 364why, one step back364 None => Time::zero(),ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 365–371why, one step back365 Some(shell) => Self::extract_time(shell),366 }367 }368}369370#[test]371fn test_mock_executor_extract_time() {Use uomDavid Peterbefore adoption641451a
lines 372–375why, one step back372 assert_eq!(373 MockExecutor::extract_time("sleep 0.1"),374 Time::from_seconds(0.1)375 );ran cargo fmtHumble Penguinbefore adoptionacf156e
line 376why, one step back376}