Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

383 lines · 11.9 KiB · Rust

Last changed by

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

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

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

lines 5–7why, one step back
5use crate::benchmark::quantity::mean;
6use crate::benchmark::quantity::Byte;7use crate::benchmark::quantity::Second;

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 8–12why, one step back
8use crate::command::Command;
9use crate::options::{10 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,11};12use crate::output::progress_bar::get_progress_bar;

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

line 13why, one step back
13use crate::quantity::{second, Information, Time, Zero};

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 15–16why, one step back
15use crate::util::randomized_environment_offset;
16

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 18–20why, one step back
18
19use anyhow::{bail, Context, Result};20

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

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 22–37why, one step back
22pub enum BenchmarkIteration {
23 NonBenchmarkRun,24 Warmup(u64),25 Benchmark(u64),26}2728impl BenchmarkIteration {29 pub fn to_env_var_value(&self) -> Option<String> {30 match self {31 BenchmarkIteration::NonBenchmarkRun => None,32 BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)),33 BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)),34 }35 }36}37

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 38–42why, one step back
38pub trait Executor {
39 /// Run the given command and measure the execution time40 fn run_command_and_measure(41 &self,42 command: &Command<'_>,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 47–57why, one step back
47
48 /// Perform a calibration of this executor. For example,49 /// when running commands through a shell, we need to50 /// measure the shell spawning time separately in order51 /// to subtract it from the full runtime later.52 fn calibrate(&mut self) -> Result<()>;5354 /// Return the time overhead for this executor when55 /// performing a measurement. This should return the time56 /// that is being used in addition to the actual runtime57 /// of the command.

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

line 58why, one step back
58 fn time_overhead(&self) -> Time;

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 59–62why, one step back
59}
6061fn run_command_and_measure_common(62 mut command: std::process::Command,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 64–67why, one step back
64 command_failure_action: CmdFailureAction,
65 command_input_policy: &CommandInputPolicy,66 command_output_policy: &CommandOutputPolicy,67 command_name: &str,

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 69–77why, one step back
69 let stdin = command_input_policy.get_stdin()?;
70 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;71 command.stdin(stdin).stdout(stdout).stderr(stderr);7273 command.env(74 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",75 randomized_environment_offset::value(),76 );77

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

style: simplify string interpolationHamir Mahalbefore adoptionef12632

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 84why, one step back
84

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

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

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

lines 86–92why, one step back
86 use crate::util::exit_code::extract_exit_code;
8788 let should_fail = match command_failure_action {89 CmdFailureAction::RaiseError => true,90 CmdFailureAction::IgnoreAllFailures => false,91 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {92 // 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 93why, one step back
93 if let Some(exit_code) = extract_exit_code(result.exit_status) {

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

lines 94–99why, one step back
94 !codes.contains(&exit_code)
95 } else {96 // If we can't extract an exit code, treat it as a failure97 true98 }99 }

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 100–101why, one step back
100 };
101

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

lines 102–112why, one step back
102 if should_fail {
103 let when = match iteration {104 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),105 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),106 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),107 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),108 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),109 };110 bail!(111 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \112 Alternatively, use the '--show-output' option to debug what went wrong.",

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

line 113why, one step back
113 cause=result.exit_status.code().map_or(

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

lines 114–119why, one step back
114 "The process has been terminated by a signal".into(),
115 |c| format!("Command terminated with non-zero exit code {c}")116117 ),118 );119 }

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 120–134why, one step back
120 }
121122 Ok(result)123}124125pub struct RawExecutor<'a> {126 options: &'a Options,127}128129impl<'a> RawExecutor<'a> {130 pub fn new(options: &'a Options) -> Self {131 RawExecutor { options }132 }133}134

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 136–138why, one step back
136 fn run_command_and_measure(
137 &self,138 command: &Command<'_>,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 145why, one step back
145 iteration,

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

line 148why, one step back
148 output_policy,

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Real => wall clockDavid Peterbefore adoptionc20fcc0

lines 150–160why, one step back
150 )?;
151152 Ok((153 TimingResult {154 time_wall_clock: result.time_wall_clock,155 time_user: result.time_user,156 time_system: result.time_system,157 memory_usage_byte: result.memory_usage_byte,158 },159 result.status,160 ))

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 161–166why, one step back
161 }
162163 fn calibrate(&mut self) -> Result<()> {164 Ok(())165 }166

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

lines 167–168why, one step back
167 fn time_overhead(&self) -> Second {
168 Second::zero()

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 169–174why, one step back
169 }
170}171172pub struct ShellExecutor<'a> {173 options: &'a Options,174 shell: &'a Shell,

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

line 175why, one step back
175 shell_spawning_time: Option<Measurement>,

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 176–187why, one step back
176}
177178impl<'a> ShellExecutor<'a> {179 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {180 ShellExecutor {181 shell,182 options,183 shell_spawning_time: None,184 }185 }186}187

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

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

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

line 199why, one step back
199

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

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

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

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

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

lines 203–206why, one step back
203 command_builder.raw_arg(command.get_command_line());
204 } else {205 command_builder.arg(command.get_command_line());206 }

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 207–209why, one step back
207
208 let mut result = run_command_and_measure_common(209 command_builder,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 210why, one step back
210 iteration,

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

line 213why, one step back
213 output_policy,

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 214–217why, one step back
214 &command.get_command_line(),
215 )?;216217 // Subtract shell spawning time

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

lines 218–225why, one step back
218 fn ensure_non_negative(time: Second) -> Second {
219 if time < Second::zero() {220 Second::zero()221 } else {222 time223 }224 }225

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

line 227why, one step back
227 result.time_wall_clock =

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

lines 228–231why, one step back
228 ensure_non_negative(result.time_wall_clock - spawning_time.time_wall_clock);
229 result.time_user = ensure_non_negative(result.time_user - spawning_time.time_user);230 result.time_system =231 ensure_non_negative(result.time_system - spawning_time.time_system);

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 232–233why, one step back
232 }
233

Real => wall clockDavid Peterbefore adoptionc20fcc0

lines 234–242why, one step back
234 Ok((
235 TimingResult {236 time_wall_clock: result.time_wall_clock,237 time_user: result.time_user,238 time_system: result.time_system,239 memory_usage_byte: result.memory_usage_byte,240 },241 result.status,242 ))

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 243–257why, one step back
243 }
244245 /// Measure the average shell spawning time246 fn calibrate(&mut self) -> Result<()> {247 const COUNT: u64 = 50;248 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {249 Some(get_progress_bar(250 COUNT,251 "Measuring shell spawning time",252 self.options.output_style,253 ))254 } else {255 None256 };257

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

line 258why, one step back
258 let mut times_wall_clock: Vec<Second> = vec![]; // TODO

Real => wall clockDavid Peterbefore adoptionc20fcc0

lines 259–260why, one step back
259 let mut times_user: Vec<Second> = vec![];
260 let mut times_system: Vec<Second> = vec![];

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 261–263why, one step back
261
262 for _ in 0..COUNT {263 // Just run the shell without any command

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 264–267why, one step back
264 let res = self.run_command_and_measure(
265 &Command::new(None, ""),266 BenchmarkIteration::NonBenchmarkRun,267 None,

Multiple output policiesDavid Peterbefore adoption99d24b7

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 269why, one step back
269 );

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 270–283why, one step back
270
271 match res {272 Err(_) => {273 let shell_cmd = if cfg!(windows) {274 format!("{} /C \"\"", self.shell)275 } else {276 format!("{} -c \"\"", self.shell)277 };278279 bail!(280 "Could not measure shell execution time. Make sure you can run '{}'.",281 shell_cmd282 );283 }

Real => wall clockDavid Peterbefore adoptionc20fcc0

lines 284–287why, one step back
284 Ok((r, _)) => {
285 times_wall_clock.push(r.time_wall_clock);286 times_user.push(r.time_user);287 times_system.push(r.time_system);

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 288–299why, one step back
288 }
289 }290291 if let Some(bar) = progress_bar.as_ref() {292 bar.inc(1)293 }294 }295296 if let Some(bar) = progress_bar.as_ref() {297 bar.finish_and_clear()298 }299

Real => wall clockDavid Peterbefore adoptionc20fcc0

lines 300–303why, one step back
300 self.shell_spawning_time = Some(TimingResult {
301 time_wall_clock: mean(&times_wall_clock),302 time_user: mean(&times_user),303 time_system: mean(&times_system),

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

line 304why, one step back
304 memory_usage_byte: Byte::new(0),

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 305–309why, one step back
305 });
306307 Ok(())308 }309

Real => wall clockDavid Peterbefore adoptionc20fcc0

line 310why, one step back
310 fn time_overhead(&self) -> Second {

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 312–324why, one step back
312 }
313}314315#[derive(Clone)]316pub struct MockExecutor {317 shell: Option<String>,318}319320impl MockExecutor {321 pub fn new(shell: Option<String>) -> Self {322 MockExecutor { shell }323 }324

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

line 327why, one step back
327 Second::new(

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

lines 328–333why, one step back
328 sleep_command
329 .as_ref()330 .trim_start_matches("sleep ")331 .parse::<f64>()332 .unwrap(),333 )

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 334–340why, one step back
334 }
335}336337impl Executor for MockExecutor {338 fn run_command_and_measure(339 &self,340 command: &Command<'_>,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 341why, one step back
341 _iteration: BenchmarkIteration,

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 347–351why, one step back
347 use std::os::unix::process::ExitStatusExt;
348 ExitStatus::from_raw(0)349 };350351 #[cfg(windows)]

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 353–356why, one step back
353 use std::os::windows::process::ExitStatusExt;
354 ExitStatus::from_raw(0)355 };356

Real => wall clockDavid Peterbefore adoptionc20fcc0

lines 357–359why, one step back
357 Ok((
358 TimingResult {359 time_wall_clock: Self::extract_time(command.get_command_line()),

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

lines 360–362why, one step back
360 time_user: Second::zero(),
361 time_system: Second::zero(),362 memory_usage_byte: Byte::new(0),

Real => wall clockDavid Peterbefore adoptionc20fcc0

lines 363–365why, one step back
363 },
364 status,365 ))

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 366–371why, one step back
366 }
367368 fn calibrate(&mut self) -> Result<()> {369 Ok(())370 }371

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

line 374why, one step back
374 None => Second::zero(),

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 375–381why, one step back
375 Some(shell) => Self::extract_time(shell),
376 }377 }378}379380#[test]381fn test_mock_executor_extract_time() {

Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299

line 382why, one step back
382 assert_eq!(MockExecutor::extract_time("sleep 0.1"), Second::new(0.1));

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 383why, one step back
383}