Skip to content
Myr

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 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–9why, one step back
3use 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 back
10use crate::quantity::{second, Information, Time, Zero};

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

line 11why, one step back
11use crate::timer::execute_and_measure;

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 12–13why, one step back
12use crate::util::randomized_environment_offset;
13

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

line 14why, one step back
14use super::measurement::{Measurement, Measurements};

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 15–17why, one step back
15
16use anyhow::{bail, Context, Result};17

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 34–38why, one step back
34pub 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 back
39 iteration: BenchmarkIteration,

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 43–53why, one step back
43
44 /// 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 back
54 fn time_overhead(&self) -> Time;

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 78why, one step back
78 let result = execute_and_measure(command)

style: simplify string interpolationHamir Mahalbefore adoptionef12632

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 80why, one step back
80

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

line 81why, one step back
81 if !result.exit_status.success() {

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

lines 82–88why, one step back
82 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 ignore

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

line 89why, one step back
89 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 back
90 !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 back
96 };
97

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

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

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

lines 110–115why, one step back
110 "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 back
116 }
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}130

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 132–134why, one step back
132 fn run_command_and_measure(
133 &self,134 command: &Command<'_>,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

lines 138–139why, one step back
138 ) -> Result<Measurement> {
139 run_command_and_measure_common(

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 141why, one step back
141 iteration,

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

line 144why, one step back
144 output_policy,

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

line 146why, one step back
146 )

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 147–152why, one step back
147 }
148149 fn calibrate(&mut self) -> Result<()> {150 Ok(())151 }152

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 155–160why, one step back
155 }
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 back
161 shell_spawning_time: Option<Measurement>,

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 175–177why, one step back
175 fn run_command_and_measure(
176 &self,177 command: &Command<'_>,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

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

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

line 185why, one step back
185

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

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

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

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

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

lines 189–192why, one step back
189 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 back
193
194 let mut result = run_command_and_measure_common(195 command_builder,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 196why, one step back
196 iteration,

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

line 199why, one step back
199 output_policy,

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 200–204why, one step back
200 &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 back
205 result.time_wall_clock =

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

lines 206–208why, one step back
206 (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 back
209 }
210

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

line 211why, one step back
211 Ok(result)

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 228–230why, one step back
228
229 for _ in 0..COUNT {230 // Just run the shell without any command

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 231–234why, one step back
231 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 back
235 &CommandOutputPolicy::Null,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 236why, one step back
236 );

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 237–250why, one step back
237
238 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 back
251 Ok(r) => {

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

line 252why, one step back
252 measurements.push(r);

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

line 265why, one step back
265 self.shell_spawning_time = Some(Measurement {

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

lines 266–268why, one step back
266 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 back
269 peak_memory_usage: measurements.peak_memory_usage_mean(),

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

line 270why, one step back
270 exit_status: ExitStatus::default(),

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 271–275why, one step back
271 });
272273 Ok(())274 }275

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

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

lines 293–299why, one step back
293 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 back
300 }
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 back
307 _iteration: BenchmarkIteration,

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 313–317why, one step back
313 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 back
318 let exit_status = {

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 319–322why, one step back
319 use std::os::windows::process::ExitStatusExt;
320 ExitStatus::from_raw(0)321 };322

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

line 323why, one step back
323 Ok(Measurement {

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

line 324why, one step back
324 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 back
325 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 back
328 exit_status,

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

line 329why, one step back
329 })

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 330–335why, one step back
330 }
331332 fn calibrate(&mut self) -> Result<()> {333 Ok(())334 }335

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 339–345why, one step back
339 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 back
346 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 back
350}