Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

376 lines · 12.1 KiB · Rust

Last changed by

RefactoringDavid Peterbefore adoption71365c2

History of this file

Take 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 back
1#[cfg(windows)]

bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea

line 2why, one step back
2use std::os::windows::process::CommandExt;

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 3–4why, one step back
3use std::process::ExitStatus;
4

Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1

lines 5–6why, one step back
5use crate::benchmark::measurement::Measurement;
6use crate::benchmark::measurement::Measurements;

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 7–11why, one step back
7use 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 back
12use 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 back
15use crate::timer::execute_and_measure;

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 16–19why, one step back
16use crate::util::randomized_environment_offset;
1718use anyhow::{bail, Context, Result};19

Merge pull request #807 from willcl-ark/expose-run-varDavid Peterbefore adoption30a2b61

line 20why, one step back
20#[derive(Clone, Copy)]

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 21–36why, one step back
21pub 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}36

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 37–41why, one step back
37pub 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 back
42 iteration: BenchmarkIteration,

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 43why, one step back
43 command_failure_action: Option<CmdFailureAction>,

Multiple output policiesDavid Peterbefore adoption99d24b7

line 44why, one step back
44 output_policy: &CommandOutputPolicy,

Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11

line 45why, one step back
45 ) -> Result<Measurement>;

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 46–56why, one step back
46
47 /// 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 back
57 fn time_overhead(&self) -> Time;

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 58–61why, one step back
58}
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 back
62 iteration: BenchmarkIteration,

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 63–66why, one step back
63 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 back
67) -> Result<Measurement> {

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 68–76why, one step back
68 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 );76

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 77–80why, one step back
77 if let Some(value) = iteration.to_env_var_value() {
78 command.env("HYPERFINE_ITERATION", value);79 }80

RefactoringDavid Peterbefore adoption71365c2

line 81why, one step back
81 let measurement = execute_and_measure(command)

style: simplify string interpolationHamir Mahalbefore adoptionef12632

line 82why, one step back
82 .with_context(|| format!("Failed to run command '{command_name}'"))?;

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 83why, one step back
83

RefactoringDavid Peterbefore adoption71365c2

lines 84–85why, one step back
84 if command_failure_action == CmdFailureAction::RaiseError && !measurement.exit_status.success()
85 {

Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1

lines 86–95why, one step back
86 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 back
96 cause=measurement.exit_status.code().map_or(

Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1

lines 97–98why, one step back
97 "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 back
99
100 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 ignore

Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1

line 105why, one step back
105 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 back
106 !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 back
112 };
113

Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860

lines 114–124why, one step back
114 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 back
125 cause=result.exit_status.code().map_or(

Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860

lines 126–131why, one step back
126 "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 back
132 }
133

RefactoringDavid Peterbefore adoption71365c2

line 134why, one step back
134 Ok(measurement)

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 135–146why, one step back
135}
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}146

apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb

line 147why, one step back
147impl Executor for RawExecutor<'_> {

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 148–150why, one step back
148 fn run_command_and_measure(
149 &self,150 command: &Command<'_>,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 151why, one step back
151 iteration: BenchmarkIteration,

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 152why, one step back
152 command_failure_action: Option<CmdFailureAction>,

Multiple output policiesDavid Peterbefore adoption99d24b7

line 153why, one step back
153 output_policy: &CommandOutputPolicy,

Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11

line 154why, one step back
154 ) -> Result<Measurement> {

RefactoringDavid Peterbefore adoption71365c2

line 155why, one step back
155 run_command_and_measure_common(

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 156why, one step back
156 command.get_command()?,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 157why, one step back
157 iteration,

Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860

line 158why, one step back
158 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 159why, one step back
159 &self.options.command_input_policy,

Multiple output policiesDavid Peterbefore adoption99d24b7

line 160why, one step back
160 output_policy,

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 161why, one step back
161 &command.get_command_line(),

RefactoringDavid Peterbefore adoption71365c2

line 162why, one step back
162 )

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 163–168why, one step back
163 }
164165 fn calibrate(&mut self) -> Result<()> {166 Ok(())167 }168

Use uomDavid Peterbefore adoption641451a

lines 169–170why, one step back
169 fn time_overhead(&self) -> Time {
170 Time::zero()

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 171–176why, one step back
171 }
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 back
177 shell_spawning_time: Option<Measurement>,

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 178–189why, one step back
178}
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}189

apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb

line 190why, one step back
190impl Executor for ShellExecutor<'_> {

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 191–193why, one step back
191 fn run_command_and_measure(
192 &self,193 command: &Command<'_>,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 194why, one step back
194 iteration: BenchmarkIteration,

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 195why, one step back
195 command_failure_action: Option<CmdFailureAction>,

Multiple output policiesDavid Peterbefore adoption99d24b7

line 196why, one step back
196 output_policy: &CommandOutputPolicy,

Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11

line 197why, one step back
197 ) -> Result<Measurement> {

bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea

line 198why, one step back
198 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 199why, one step back
199 let mut command_builder = self.shell.command();

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

line 200why, one step back
200 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });

bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea

line 201why, one step back
201

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

lines 202–203why, one step back
202 // Windows needs special treatment for its behavior on parsing cmd arguments
203 if on_windows_cmd {

cfg: adding more pre-processing for windows-only parserPedro Witzelbefore adoptionae9b0bb

line 204why, one step back
204 #[cfg(windows)]

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

lines 205–208why, one step back
205 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 back
209

RefactoringDavid Peterbefore adoption71365c2

line 210why, one step back
210 let mut measurement = run_command_and_measure_common(

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 211why, one step back
211 command_builder,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 212why, one step back
212 iteration,

Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860

line 213why, one step back
213 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 214why, one step back
214 &self.options.command_input_policy,

Multiple output policiesDavid Peterbefore adoption99d24b7

line 215why, one step back
215 output_policy,

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 216–219why, one step back
216 &command.get_command_line(),
217 )?;218219 // Subtract shell spawning time

Use uomDavid Peterbefore adoption641451a

lines 220–222why, one step back
220 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 back
223 } else {
224 time225 }226 }227

Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1

line 228why, one step back
228 if let Some(ref spawning_time) = self.shell_spawning_time {

RefactoringDavid Peterbefore adoption71365c2

lines 229–234why, one step back
229 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 back
235 }
236

RefactoringDavid Peterbefore adoption71365c2

line 237why, one step back
237 Ok(measurement)

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 238–252why, one step back
238 }
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 };252

Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1

line 253why, one step back
253 let mut measurements = Measurements::default();

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 254–256why, one step back
254
255 for _ in 0..COUNT {256 // Just run the shell without any command

Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1

line 257why, one step back
257 let measurement = self.run_command_and_measure(

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 258–260why, one step back
258 &Command::new(None, ""),
259 BenchmarkIteration::NonBenchmarkRun,260 None,

Multiple output policiesDavid Peterbefore adoption99d24b7

line 261why, one step back
261 &CommandOutputPolicy::Null,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 262why, one step back
262 );

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 263why, one step back
263

Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1

line 264why, one step back
264 match measurement {

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 265–276why, one step back
265 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 back
277 Ok(result) => {
278 measurements.push(result);

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 279–290why, one step back
279 }
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 }290

Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1

lines 291–296why, one step back
291 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 back
297 });
298299 Ok(())300 }301

Use uomDavid Peterbefore adoption641451a

line 302why, one step back
302 fn time_overhead(&self) -> Time {

Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1

line 303why, one step back
303 self.shell_spawning_time.as_ref().unwrap().time_wall_clock

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 304–316why, one step back
304 }
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 }316

Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c

line 317why, one step back
317 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 318why, one step back
318 assert!(sleep_command.as_ref().starts_with("sleep "));

Use uomDavid Peterbefore adoption641451a

line 319why, one step back
319 Time::from_seconds(

Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c

lines 320–325why, one step back
320 sleep_command
321 .as_ref()322 .trim_start_matches("sleep ")323 .parse::<f64>()324 .unwrap(),325 )

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 326–332why, one step back
326 }
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 back
333 _iteration: BenchmarkIteration,

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 334why, one step back
334 _command_failure_action: Option<CmdFailureAction>,

Multiple output policiesDavid Peterbefore adoption99d24b7

line 335why, one step back
335 _output_policy: &CommandOutputPolicy,

Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11

line 336why, one step back
336 ) -> Result<Measurement> {

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 337why, one step back
337 #[cfg(unix)]

Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1

line 338why, one step back
338 let exit_status = {

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 339–343why, one step back
339 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 back
344 let exit_status = {

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 345–348why, one step back
345 use std::os::windows::process::ExitStatusExt;
346 ExitStatus::from_raw(0)347 };348

Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1

lines 349–350why, one step back
349 Ok(Measurement {
350 time_wall_clock: Self::extract_time(command.get_command_line()),

Use uomDavid Peterbefore adoption641451a

lines 351–353why, one step back
351 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 back
354 exit_status,
355 })

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 356–361why, one step back
356 }
357358 fn calibrate(&mut self) -> Result<()> {359 Ok(())360 }361

Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c

line 362why, one step back
362 fn time_overhead(&self) -> Time {

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 363why, one step back
363 match &self.shell {

Use uomDavid Peterbefore adoption641451a

line 364why, one step back
364 None => Time::zero(),

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 365–371why, one step back
365 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 back
372 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 back
376}