executor.rs
This file
Path
src/benchmark/executor.rs
350 lines · 10.8 KiB · Rust
Last changed by
Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9
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–9why, one step back3use std::process::ExitStatus;45use crate::command::Command;6use crate::options::{7 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,8};9use crate::output::progress_bar::get_progress_bar;Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 10why, one step back10use crate::quantity::{second, Information, Time, Zero};Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 11why, one step back11use crate::timer::execute_and_measure;ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 12–13why, one step back12use crate::util::randomized_environment_offset;13Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 14why, one step back14use super::measurement::{Measurement, Measurements};ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 15–17why, one step back1516use anyhow::{bail, Context, Result};17Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 18–33why, one step back18pub enum BenchmarkIteration {19 NonBenchmarkRun,20 Warmup(u64),21 Benchmark(u64),22}2324impl BenchmarkIteration {25 pub fn to_env_var_value(&self) -> Option<String> {26 match self {27 BenchmarkIteration::NonBenchmarkRun => None,28 BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)),29 BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)),30 }31 }32}33ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 34–38why, one step back34pub trait Executor {35 /// Run the given command and measure the execution time36 fn run_command_and_measure(37 &self,38 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 39why, one step back39 iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 40why, one step back40 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 41why, one step back41 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 42why, one step back42 ) -> Result<Measurement>;ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 43–53why, one step back4344 /// Perform a calibration of this executor. For example,45 /// when running commands through a shell, we need to46 /// measure the shell spawning time separately in order47 /// to subtract it from the full runtime later.48 fn calibrate(&mut self) -> Result<()>;4950 /// Return the time overhead for this executor when51 /// performing a measurement. This should return the time52 /// that is being used in addition to the actual runtime53 /// of the command.Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 54why, one step back54 fn time_overhead(&self) -> Time;ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 55–58why, one step back55}5657fn run_command_and_measure_common(58 mut command: std::process::Command,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 59why, one step back59 iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 60–63why, one step back60 command_failure_action: CmdFailureAction,61 command_input_policy: &CommandInputPolicy,62 command_output_policy: &CommandOutputPolicy,63 command_name: &str,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 64why, one step back64) -> Result<Measurement> {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 65–73why, one step back65 let stdin = command_input_policy.get_stdin()?;66 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;67 command.stdin(stdin).stdout(stdout).stderr(stderr);6869 command.env(70 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",71 randomized_environment_offset::value(),72 );73Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 74–77why, one step back74 if let Some(value) = iteration.to_env_var_value() {75 command.env("HYPERFINE_ITERATION", value);76 }77ran cargo fmtHumble Penguinbefore adoptionacf156e
line 78why, one step back78 let result = execute_and_measure(command)style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 79why, one step back79 .with_context(|| format!("Failed to run command '{command_name}'"))?;ran cargo fmtHumble Penguinbefore adoptionacf156e
line 80why, one step back80Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 81why, one step back81 if !result.exit_status.success() {Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 82–88why, one step back82 use crate::util::exit_code::extract_exit_code;8384 let should_fail = match command_failure_action {85 CmdFailureAction::RaiseError => true,86 CmdFailureAction::IgnoreAllFailures => false,87 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {88 // 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 89why, one step back89 if let Some(exit_code) = extract_exit_code(result.exit_status) {Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 90–95why, one step back90 !codes.contains(&exit_code)91 } else {92 // If we can't extract an exit code, treat it as a failure93 true94 }95 }Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 96–97why, one step back96 };97Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 98–108why, one step back98 if should_fail {99 let when = match iteration {100 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),101 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),102 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),103 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),104 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),105 };106 bail!(107 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \108 Alternatively, use the '--show-output' option to debug what went wrong.",Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 109why, one step back109 cause=result.exit_status.code().map_or(Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 110–115why, one step back110 "The process has been terminated by a signal".into(),111 |c| format!("Command terminated with non-zero exit code {c}")112113 ),114 );115 }ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 116–130why, one step back116 }117118 Ok(result)119}120121pub struct RawExecutor<'a> {122 options: &'a Options,123}124125impl<'a> RawExecutor<'a> {126 pub fn new(options: &'a Options) -> Self {127 RawExecutor { options }128 }129}130apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 131why, one step back131impl Executor for RawExecutor<'_> {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 132–134why, one step back132 fn run_command_and_measure(133 &self,134 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 135why, one step back135 iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 136why, one step back136 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 137why, one step back137 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
lines 138–139why, one step back138 ) -> Result<Measurement> {139 run_command_and_measure_common(ran cargo fmtHumble Penguinbefore adoptionacf156e
line 140why, one step back140 command.get_command()?,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 141why, one step back141 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 142why, one step back142 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),ran cargo fmtHumble Penguinbefore adoptionacf156e
line 143why, one step back143 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 144why, one step back144 output_policy,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 145why, one step back145 &command.get_command_line(),Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 146why, one step back146 )ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 147–152why, one step back147 }148149 fn calibrate(&mut self) -> Result<()> {150 Ok(())151 }152Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
lines 153–154why, one step back153 fn time_overhead(&self) -> Time {154 Time::zero()ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 155–160why, one step back155 }156}157158pub struct ShellExecutor<'a> {159 options: &'a Options,160 shell: &'a Shell,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 161why, one step back161 shell_spawning_time: Option<Measurement>,ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 162–173why, one step back162}163164impl<'a> ShellExecutor<'a> {165 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {166 ShellExecutor {167 shell,168 options,169 shell_spawning_time: None,170 }171 }172}173apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 174why, one step back174impl Executor for ShellExecutor<'_> {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 175–177why, one step back175 fn run_command_and_measure(176 &self,177 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 178why, one step back178 iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 179why, one step back179 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 180why, one step back180 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 181why, one step back181 ) -> Result<Measurement> { bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 182why, one step back182 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");ran cargo fmtHumble Penguinbefore adoptionacf156e
line 183why, one step back183 let mut command_builder = self.shell.command();fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
line 184why, one step back184 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" }); bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 185why, one step back185fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 186–187why, one step back186 // Windows needs special treatment for its behavior on parsing cmd arguments187 if on_windows_cmd {cfg: adding more pre-processing for windows-only parserPedro Witzelbefore adoptionae9b0bb
line 188why, one step back188 #[cfg(windows)]fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 189–192why, one step back189 command_builder.raw_arg(command.get_command_line());190 } else {191 command_builder.arg(command.get_command_line());192 }ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 193–195why, one step back193194 let mut result = run_command_and_measure_common(195 command_builder,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 196why, one step back196 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 197why, one step back197 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),ran cargo fmtHumble Penguinbefore adoptionacf156e
line 198why, one step back198 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 199why, one step back199 output_policy,ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 200–204why, one step back200 &command.get_command_line(),201 )?;202203 // Subtract shell spawning time204 if let Some(spawning_time) = self.shell_spawning_time {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 205why, one step back205 result.time_wall_clock =Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
lines 206–208why, one step back206 (result.time_wall_clock - spawning_time.time_wall_clock).max(Time::zero());207 result.time_user = (result.time_user - spawning_time.time_user).max(Time::zero());208 result.time_system = (result.time_system - spawning_time.time_system).max(Time::zero());ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 209–210why, one step back209 }210Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 211why, one step back211 Ok(result)ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 212–226why, one step back212 }213214 /// Measure the average shell spawning time215 fn calibrate(&mut self) -> Result<()> {216 const COUNT: u64 = 50;217 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {218 Some(get_progress_bar(219 COUNT,220 "Measuring shell spawning time",221 self.options.output_style,222 ))223 } else {224 None225 };226Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 227why, one step back227 let mut measurements = Measurements::default();ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 228–230why, one step back228229 for _ in 0..COUNT {230 // Just run the shell without any commandAdd iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 231–234why, one step back231 let res = self.run_command_and_measure(232 &Command::new(None, ""),233 BenchmarkIteration::NonBenchmarkRun,234 None,Multiple output policiesDavid Peterbefore adoption99d24b7
line 235why, one step back235 &CommandOutputPolicy::Null,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 236why, one step back236 );ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 237–250why, one step back237238 match res {239 Err(_) => {240 let shell_cmd = if cfg!(windows) {241 format!("{} /C \"\"", self.shell)242 } else {243 format!("{} -c \"\"", self.shell)244 };245246 bail!(247 "Could not measure shell execution time. Make sure you can run '{}'.",248 shell_cmd249 );250 }Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 251why, one step back251 Ok(r) => {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 252why, one step back252 measurements.push(r);ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 253–264why, one step back253 }254 }255256 if let Some(bar) = progress_bar.as_ref() {257 bar.inc(1)258 }259 }260261 if let Some(bar) = progress_bar.as_ref() {262 bar.finish_and_clear()263 }264Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 265why, one step back265 self.shell_spawning_time = Some(Measurement {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
lines 266–268why, one step back266 time_wall_clock: measurements.time_wall_clock_mean(),267 time_user: measurements.time_user_mean(),268 time_system: measurements.time_system_mean(),Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9
line 269why, one step back269 peak_memory_usage: measurements.peak_memory_usage_mean(),Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 270why, one step back270 exit_status: ExitStatus::default(),ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 271–275why, one step back271 });272273 Ok(())274 }275Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 276why, one step back276 fn time_overhead(&self) -> Time {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 277why, one step back277 self.shell_spawning_time.unwrap().time_wall_clockran cargo fmtHumble Penguinbefore adoptionacf156e
lines 278–290why, one step back278 }279}280281#[derive(Clone)]282pub struct MockExecutor {283 shell: Option<String>,284}285286impl MockExecutor {287 pub fn new(shell: Option<String>) -> Self {288 MockExecutor { shell }289 }290Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 291why, one step back291 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {ran cargo fmtHumble Penguinbefore adoptionacf156e
line 292why, one step back292 assert!(sleep_command.as_ref().starts_with("sleep "));Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
lines 293–299why, one step back293 Time::new::<second>(294 sleep_command295 .as_ref()296 .trim_start_matches("sleep ")297 .parse::<f64>()298 .unwrap(),299 )ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 300–306why, one step back300 }301}302303impl Executor for MockExecutor {304 fn run_command_and_measure(305 &self,306 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 307why, one step back307 _iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 308why, one step back308 _command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 309why, one step back309 _output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 310why, one step back310 ) -> Result<Measurement> {ran cargo fmtHumble Penguinbefore adoptionacf156e
line 311why, one step back311 #[cfg(unix)]Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 312why, one step back312 let exit_status = {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 313–317why, one step back313 use std::os::unix::process::ExitStatusExt;314 ExitStatus::from_raw(0)315 };316317 #[cfg(windows)]Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 318why, one step back318 let exit_status = {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 319–322why, one step back319 use std::os::windows::process::ExitStatusExt;320 ExitStatus::from_raw(0)321 };322Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 323why, one step back323 Ok(Measurement {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 324why, one step back324 time_wall_clock: Self::extract_time(command.get_command_line()),Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
lines 325–327why, one step back325 time_user: Time::zero(),326 time_system: Time::zero(),327 peak_memory_usage: Information::zero(),Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 328why, one step back328 exit_status,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 329why, one step back329 })ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 330–335why, one step back330 }331332 fn calibrate(&mut self) -> Result<()> {333 Ok(())334 }335Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 336why, one step back336 fn time_overhead(&self) -> Time {ran cargo fmtHumble Penguinbefore adoptionacf156e
line 337why, one step back337 match &self.shell {Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 338why, one step back338 None => Time::zero(),ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 339–345why, one step back339 Some(shell) => Self::extract_time(shell),340 }341 }342}343344#[test]345fn test_mock_executor_extract_time() {Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
lines 346–349why, one step back346 assert_eq!(347 MockExecutor::extract_time("sleep 0.1"),348 Time::new::<second>(0.1)349 );ran cargo fmtHumble Penguinbefore adoptionacf156e
line 350why, one step back350}