Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

351 lines · 10.8 KiB · Rust

Last changed by

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

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

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

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 19–34why, one step back
19pub enum BenchmarkIteration {
20 NonBenchmarkRun,21 Warmup(u64),22 Benchmark(u64),23}2425impl BenchmarkIteration {26 pub fn to_env_var_value(&self) -> Option<String> {27 match self {28 BenchmarkIteration::NonBenchmarkRun => None,29 BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)),30 BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)),31 }32 }33}34

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 44–54why, one step back
44
45 /// Perform a calibration of this executor. For example,46 /// when running commands through a shell, we need to47 /// measure the shell spawning time separately in order48 /// to subtract it from the full runtime later.49 fn calibrate(&mut self) -> Result<()>;5051 /// Return the time overhead for this executor when52 /// performing a measurement. This should return the time53 /// that is being used in addition to the actual runtime54 /// of the command.

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 61–64why, one step back
61 command_failure_action: CmdFailureAction,
62 command_input_policy: &CommandInputPolicy,63 command_output_policy: &CommandOutputPolicy,64 command_name: &str,

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 66–74why, one step back
66 let stdin = command_input_policy.get_stdin()?;
67 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;68 command.stdin(stdin).stdout(stdout).stderr(stderr);6970 command.env(71 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",72 randomized_environment_offset::value(),73 );74

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

style: simplify string interpolationHamir Mahalbefore adoptionef12632

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 81why, one step back
81

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

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

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

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

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

lines 91–96why, one step back
91 !codes.contains(&exit_code)
92 } else {93 // If we can't extract an exit code, treat it as a failure94 true95 }96 }

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 97–98why, one step back
97 };
98

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

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

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

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 117–131why, one step back
117 }
118119 Ok(result)120}121122pub struct RawExecutor<'a> {123 options: &'a Options,124}125126impl<'a> RawExecutor<'a> {127 pub fn new(options: &'a Options) -> Self {128 RawExecutor { options }129 }130}131

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 142why, one step back
142 iteration,

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

line 145why, one step back
145 output_policy,

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

line 147why, one step back
147 )

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 148–153why, one step back
148 }
149150 fn calibrate(&mut self) -> Result<()> {151 Ok(())152 }153

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 156–161why, one step back
156 }
157}158159pub struct ShellExecutor<'a> {160 options: &'a Options,161 shell: &'a Shell,

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 163–174why, one step back
163}
164165impl<'a> ShellExecutor<'a> {166 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {167 ShellExecutor {168 shell,169 options,170 shell_spawning_time: None,171 }172 }173}174

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

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

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

line 186why, one step back
186

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

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

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

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

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

lines 190–193why, one step back
190 command_builder.raw_arg(command.get_command_line());
191 } else {192 command_builder.arg(command.get_command_line());193 }

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 194–196why, one step back
194
195 let mut result = run_command_and_measure_common(196 command_builder,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 197why, one step back
197 iteration,

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

line 200why, one step back
200 output_policy,

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 201–205why, one step back
201 &command.get_command_line(),
202 )?;203204 // Subtract shell spawning time205 if let Some(spawning_time) = self.shell_spawning_time {

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

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

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

lines 207–209why, one step back
207 (result.time_wall_clock - spawning_time.time_wall_clock).max(Time::zero());
208 result.time_user = (result.time_user - spawning_time.time_user).max(Time::zero());209 result.time_system = (result.time_system - spawning_time.time_system).max(Time::zero());

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 210–211why, one step back
210 }
211

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 213–227why, one step back
213 }
214215 /// Measure the average shell spawning time216 fn calibrate(&mut self) -> Result<()> {217 const COUNT: u64 = 50;218 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {219 Some(get_progress_bar(220 COUNT,221 "Measuring shell spawning time",222 self.options.output_style,223 ))224 } else {225 None226 };227

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 232–235why, one step back
232 let res = self.run_command_and_measure(
233 &Command::new(None, ""),234 BenchmarkIteration::NonBenchmarkRun,235 None,

Multiple output policiesDavid Peterbefore adoption99d24b7

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 237why, one step back
237 );

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 238–251why, one step back
238
239 match res {240 Err(_) => {241 let shell_cmd = if cfg!(windows) {242 format!("{} /C \"\"", self.shell)243 } else {244 format!("{} -c \"\"", self.shell)245 };246247 bail!(248 "Could not measure shell execution time. Make sure you can run '{}'.",249 shell_cmd250 );251 }

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

line 252why, one step back
252 Ok(r) => {

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 254–265why, one step back
254 }
255 }256257 if let Some(bar) = progress_bar.as_ref() {258 bar.inc(1)259 }260 }261262 if let Some(bar) = progress_bar.as_ref() {263 bar.finish_and_clear()264 }265

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

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

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

lines 267–269why, one step back
267 time_wall_clock: measurements.time_wall_clock_mean(),
268 time_user: measurements.time_user_mean(),269 time_system: measurements.time_system_mean(),

Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9

line 270why, one step back
270 peak_memory_usage: measurements.peak_memory_usage_mean(),

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 272–276why, one step back
272 });
273274 Ok(())275 }276

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

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 279–291why, one step back
279 }
280}281282#[derive(Clone)]283pub struct MockExecutor {284 shell: Option<String>,285}286287impl MockExecutor {288 pub fn new(shell: Option<String>) -> Self {289 MockExecutor { shell }290 }291

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

lines 294–300why, one step back
294 Time::new::<second>(
295 sleep_command296 .as_ref()297 .trim_start_matches("sleep ")298 .parse::<f64>()299 .unwrap(),300 )

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 301–307why, one step back
301 }
302}303304impl Executor for MockExecutor {305 fn run_command_and_measure(306 &self,307 command: &Command<'_>,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 314–318why, one step back
314 use std::os::unix::process::ExitStatusExt;
315 ExitStatus::from_raw(0)316 };317318 #[cfg(windows)]

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

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

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

line 325why, one step back
325 time_wall_clock: Self::extract_time(command.get_command_line()),

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

lines 326–328why, one step back
326 time_user: Time::zero(),
327 time_system: Time::zero(),328 peak_memory_usage: Information::zero(),

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

line 329why, one step back
329 exit_status,

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

line 330why, one step back
330 })

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 331–336why, one step back
331 }
332333 fn calibrate(&mut self) -> Result<()> {334 Ok(())335 }336

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

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

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

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

ran cargo fmtHumble Penguinbefore adoptionacf156e

lines 340–346why, one step back
340 Some(shell) => Self::extract_time(shell),
341 }342 }343}344345#[test]346fn test_mock_executor_extract_time() {

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

lines 347–350why, one step back
347 assert_eq!(
348 MockExecutor::extract_time("sleep 0.1"),349 Time::new::<second>(0.1)350 );

ran cargo fmtHumble Penguinbefore adoptionacf156e

line 351why, one step back
351}