executor.rs
This file
Path
src/benchmark/executor.rs
388 lines · 12.6 KiB · Rust
Last changed by
Use uomDavid Peterbefore adoption641451a
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;Use uomDavid Peterbefore adoption641451a
lines 7–9why, one step back7use crate::benchmark::quantity::Information;8use crate::benchmark::quantity::InformationQuantity;9use crate::benchmark::quantity::{Time, TimeQuantity};ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 10–14why, one step back10use crate::command::Command;11use crate::options::{12 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,13};14use crate::output::progress_bar::get_progress_bar;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 }80ran cargo fmtHumble Penguinbefore adoptionacf156e
line 81why, one step back81 let result = 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 back83Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 84–97why, one step back84 if command_failure_action == CmdFailureAction::RaiseError && !result.exit_status.success() {85 let when = match iteration {86 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),87 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),88 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),89 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),90 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),91 };92 bail!(93 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \94 Alternatively, use the '--show-output' option to debug what went wrong.",95 cause=result.exit_status.code().map_or(96 "The process has been terminated by a signal".into(),97 |c| format!("Command terminated with non-zero exit code {c}")Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 98–103why, one step back9899 let should_fail = match command_failure_action {100 CmdFailureAction::RaiseError => true,101 CmdFailureAction::IgnoreAllFailures => false,102 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {103 // 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 104why, one step back104 if let Some(exit_code) = extract_exit_code(result.exit_status) {Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 105–110why, one step back105 !codes.contains(&exit_code)106 } else {107 // If we can't extract an exit code, treat it as a failure108 true109 }110 }Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 111–112why, one step back111 };112Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 113–123why, one step back113 if should_fail {114 let when = match iteration {115 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),116 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),117 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),118 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),119 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),120 };121 bail!(122 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \123 Alternatively, use the '--show-output' option to debug what went wrong.",Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 124why, one step back124 cause=result.exit_status.code().map_or(Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 125–130why, one step back125 "The process has been terminated by a signal".into(),126 |c| format!("Command terminated with non-zero exit code {c}")127128 ),129 );130 }ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 131–145why, one step back131 }132133 Ok(result)134}135136pub struct RawExecutor<'a> {137 options: &'a Options,138}139140impl<'a> RawExecutor<'a> {141 pub fn new(options: &'a Options) -> Self {142 RawExecutor { options }143 }144}145apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 146why, one step back146impl Executor for RawExecutor<'_> {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 147–149why, one step back147 fn run_command_and_measure(148 &self,149 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 150why, one step back150 iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 151why, one step back151 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 152why, one step back152 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 153why, one step back153 ) -> Result<Measurement> {Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 154why, one step back154 let result = run_command_and_measure_common(ran cargo fmtHumble Penguinbefore adoptionacf156e
line 155why, one step back155 command.get_command()?,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 156why, one step back156 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 157why, one step back157 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),ran cargo fmtHumble Penguinbefore adoptionacf156e
line 158why, one step back158 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 159why, one step back159 output_policy,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 160why, one step back160 &command.get_command_line(),Real => wall clockDavid Peterbefore adoptionc20fcc0
lines 161–162why, one step back161 )?;162Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 163–169why, one step back163 Ok(Measurement {164 time_wall_clock: result.time_wall_clock,165 time_user: result.time_user,166 time_system: result.time_system,167 peak_memory_usage: result.peak_memory_usage,168 exit_status: result.exit_status,169 })ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 170–175why, one step back170 }171172 fn calibrate(&mut self) -> Result<()> {173 Ok(())174 }175Use uomDavid Peterbefore adoption641451a
lines 176–177why, one step back176 fn time_overhead(&self) -> Time {177 Time::zero()ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 178–183why, one step back178 }179}180181pub struct ShellExecutor<'a> {182 options: &'a Options,183 shell: &'a Shell,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 184why, one step back184 shell_spawning_time: Option<Measurement>,ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 185–196why, one step back185}186187impl<'a> ShellExecutor<'a> {188 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {189 ShellExecutor {190 shell,191 options,192 shell_spawning_time: None,193 }194 }195}196apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 197why, one step back197impl Executor for ShellExecutor<'_> {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 198–200why, one step back198 fn run_command_and_measure(199 &self,200 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 201why, one step back201 iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 202why, one step back202 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 203why, one step back203 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 204why, one step back204 ) -> Result<Measurement> { bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 205why, one step back205 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");ran cargo fmtHumble Penguinbefore adoptionacf156e
line 206why, one step back206 let mut command_builder = self.shell.command();fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
line 207why, one step back207 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" }); bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 208why, one step back208fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 209–210why, one step back209 // Windows needs special treatment for its behavior on parsing cmd arguments210 if on_windows_cmd {cfg: adding more pre-processing for windows-only parserPedro Witzelbefore adoptionae9b0bb
line 211why, one step back211 #[cfg(windows)]fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 212–215why, one step back212 command_builder.raw_arg(command.get_command_line());213 } else {214 command_builder.arg(command.get_command_line());215 }ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 216–218why, one step back216217 let mut result = run_command_and_measure_common(218 command_builder,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 219why, one step back219 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 220why, one step back220 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),ran cargo fmtHumble Penguinbefore adoptionacf156e
line 221why, one step back221 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 222why, one step back222 output_policy,ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 223–226why, one step back223 &command.get_command_line(),224 )?;225226 // Subtract shell spawning timeUse uomDavid Peterbefore adoption641451a
lines 227–229why, one step back227 fn ensure_non_negative(time: Time) -> Time {228 if time < Time::zero() {229 Time::zero()Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299
lines 230–234why, one step back230 } else {231 time232 }233 }234Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 235why, one step back235 if let Some(ref spawning_time) = self.shell_spawning_time {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 236why, one step back236 result.time_wall_clock =Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299
lines 237–240why, one step back237 ensure_non_negative(result.time_wall_clock - spawning_time.time_wall_clock);238 result.time_user = ensure_non_negative(result.time_user - spawning_time.time_user);239 result.time_system =240 ensure_non_negative(result.time_system - spawning_time.time_system);ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 241–242why, one step back241 }242Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 243–249why, one step back243 Ok(Measurement {244 time_wall_clock: result.time_wall_clock,245 time_user: result.time_user,246 time_system: result.time_system,247 peak_memory_usage: result.peak_memory_usage,248 exit_status: result.exit_status,249 })ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 250–264why, one step back250 }251252 /// Measure the average shell spawning time253 fn calibrate(&mut self) -> Result<()> {254 const COUNT: u64 = 50;255 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {256 Some(get_progress_bar(257 COUNT,258 "Measuring shell spawning time",259 self.options.output_style,260 ))261 } else {262 None263 };264Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 265why, one step back265 let mut measurements = Measurements::default();ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 266–268why, one step back266267 for _ in 0..COUNT {268 // Just run the shell without any commandUnify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 269why, one step back269 let measurement = self.run_command_and_measure(Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 270–272why, one step back270 &Command::new(None, ""),271 BenchmarkIteration::NonBenchmarkRun,272 None,Multiple output policiesDavid Peterbefore adoption99d24b7
line 273why, one step back273 &CommandOutputPolicy::Null,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 274why, one step back274 );ran cargo fmtHumble Penguinbefore adoptionacf156e
line 275why, one step back275Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 276why, one step back276 match measurement {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 277–288why, one step back277 Err(_) => {278 let shell_cmd = if cfg!(windows) {279 format!("{} /C \"\"", self.shell)280 } else {281 format!("{} -c \"\"", self.shell)282 };283284 bail!(285 "Could not measure shell execution time. Make sure you can run '{}'.",286 shell_cmd287 );288 }Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 289–290why, one step back289 Ok(result) => {290 measurements.push(result);ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 291–302why, one step back291 }292 }293294 if let Some(bar) = progress_bar.as_ref() {295 bar.inc(1)296 }297 }298299 if let Some(bar) = progress_bar.as_ref() {300 bar.finish_and_clear()301 }302Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 303–308why, one step back303 self.shell_spawning_time = Some(Measurement {304 time_wall_clock: measurements.time_wall_clock_mean(),305 time_user: measurements.time_user_mean(),306 time_system: measurements.time_system_mean(),307 peak_memory_usage: measurements.peak_memory_usage_mean(),308 exit_status: ExitStatus::default(),ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 309–313why, one step back309 });310311 Ok(())312 }313Use uomDavid Peterbefore adoption641451a
line 314why, one step back314 fn time_overhead(&self) -> Time {Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 315why, one step back315 self.shell_spawning_time.as_ref().unwrap().time_wall_clockran cargo fmtHumble Penguinbefore adoptionacf156e
lines 316–328why, one step back316 }317}318319#[derive(Clone)]320pub struct MockExecutor {321 shell: Option<String>,322}323324impl MockExecutor {325 pub fn new(shell: Option<String>) -> Self {326 MockExecutor { shell }327 }328Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 329why, one step back329 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {ran cargo fmtHumble Penguinbefore adoptionacf156e
line 330why, one step back330 assert!(sleep_command.as_ref().starts_with("sleep "));Use uomDavid Peterbefore adoption641451a
line 331why, one step back331 Time::from_seconds(Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
lines 332–337why, one step back332 sleep_command333 .as_ref()334 .trim_start_matches("sleep ")335 .parse::<f64>()336 .unwrap(),337 )ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 338–344why, one step back338 }339}340341impl Executor for MockExecutor {342 fn run_command_and_measure(343 &self,344 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 345why, one step back345 _iteration: BenchmarkIteration,ran cargo fmtHumble Penguinbefore adoptionacf156e
line 346why, one step back346 _command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 347why, one step back347 _output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 348why, one step back348 ) -> Result<Measurement> {ran cargo fmtHumble Penguinbefore adoptionacf156e
line 349why, one step back349 #[cfg(unix)]Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 350why, one step back350 let exit_status = {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 351–355why, one step back351 use std::os::unix::process::ExitStatusExt;352 ExitStatus::from_raw(0)353 };354355 #[cfg(windows)]Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 356why, one step back356 let exit_status = {ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 357–360why, one step back357 use std::os::windows::process::ExitStatusExt;358 ExitStatus::from_raw(0)359 };360Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 361–362why, one step back361 Ok(Measurement {362 time_wall_clock: Self::extract_time(command.get_command_line()),Use uomDavid Peterbefore adoption641451a
lines 363–365why, one step back363 time_user: Time::zero(),364 time_system: Time::zero(),365 peak_memory_usage: Information::from_bytes(0),Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 366–367why, one step back366 exit_status,367 })ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 368–373why, one step back368 }369370 fn calibrate(&mut self) -> Result<()> {371 Ok(())372 }373Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 374why, one step back374 fn time_overhead(&self) -> Time {ran cargo fmtHumble Penguinbefore adoptionacf156e
line 375why, one step back375 match &self.shell {Use uomDavid Peterbefore adoption641451a
line 376why, one step back376 None => Time::zero(),ran cargo fmtHumble Penguinbefore adoptionacf156e
lines 377–383why, one step back377 Some(shell) => Self::extract_time(shell),378 }379 }380}381382#[test]383fn test_mock_executor_extract_time() {Use uomDavid Peterbefore adoption641451a
lines 384–387why, one step back384 assert_eq!(385 MockExecutor::extract_time("sleep 0.1"),386 Time::from_seconds(0.1)387 );ran cargo fmtHumble Penguinbefore adoptionacf156e
line 388why, one step back388}