Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

350 lines · 10.6 KiB · Rust

Last changed by

Initial work on tracking memory usageDavid Peterbefore adoption6556b2b

History of this file

Take it

The walk stopped after 200 commits: lines older than 2e8ce30 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;

Add the rest of the suggestions from code reviewSteve Neasebefore adoptiond32b90e

line 3why, one step back
3use std::process::ExitStatus;

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 4–5why, one step back
4
5use crate::command::Command;

ran cargo fmtSteve Neasebefore adoption0e3bad1

lines 6–8why, one step back
6use crate::options::{
7 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,8};

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 9–18why, one step back
9use crate::output::progress_bar::get_progress_bar;
10use crate::timer::{execute_and_measure, TimerResult};11use crate::util::randomized_environment_offset;12use crate::util::units::Second;1314use super::timing_result::TimingResult;1516use anyhow::{bail, Context, Result};17use statistical::mean;18

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

Shrink unsafe blockcactterbefore adoption2e8ce30

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,

Shrink unsafe blockcactterbefore adoption2e8ce30

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,

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 43–59why, one step back
43 ) -> Result<(TimingResult, ExitStatus)>;
4445 /// 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.55 fn time_overhead(&self) -> Second;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,

Shrink unsafe blockcactterbefore adoption2e8ce30

line 61why, one step back
61 command_failure_action: CmdFailureAction,

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

line 62why, one step back
62 command_input_policy: &CommandInputPolicy,

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 63–65why, one step back
63 command_output_policy: &CommandOutputPolicy,
64 command_name: &str,65) -> Result<TimerResult> {

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

line 66why, one step back
66 let stdin = command_input_policy.get_stdin()?;

Change order of input/oututDavid Peterbefore adoptione88fa27

line 67why, one step back
67 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

line 68why, one step back
68 command.stdin(stdin).stdout(stdout).stderr(stderr);

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 69–74why, one step back
69
70 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

Shrink unsafe blockcactterbefore adoption2e8ce30

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}'"))?;

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 81–82why, one step back
81
82 if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 83–89why, one step back
83 let when = match iteration {
84 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),85 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),86 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),87 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),88 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),89 };

Shrink unsafe blockcactterbefore adoption2e8ce30

line 90why, one step back
90 bail!(

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 91why, one step back
91 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \

Shrink unsafe blockcactterbefore adoption2e8ce30

line 92why, one step back
92 Alternatively, use the '--show-output' option to debug what went wrong.",

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 93why, one step back
93 cause=result.status.code().map_or(

Shrink unsafe blockcactterbefore adoption2e8ce30

line 94why, one step back
94 "The process has been terminated by a signal".into(),

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

lines 95–97why, one step back
95 |c| format!("Command terminated with non-zero exit code {c}")
9697 ),

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 98–113why, one step back
98 );
99 }100101 Ok(result)102}103104pub struct RawExecutor<'a> {105 options: &'a Options,106}107108impl<'a> RawExecutor<'a> {109 pub fn new(options: &'a Options) -> Self {110 RawExecutor { options }111 }112}113

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

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

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 115–117why, one step back
115 fn run_command_and_measure(
116 &self,117 command: &Command<'_>,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

Shrink unsafe blockcactterbefore adoption2e8ce30

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 121–123why, one step back
121 ) -> Result<(TimingResult, ExitStatus)> {
122 let result = run_command_and_measure_common(123 command.get_command()?,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 124why, one step back
124 iteration,

Shrink unsafe blockcactterbefore adoption2e8ce30

line 125why, one step back
125 command_failure_action.unwrap_or(self.options.command_failure_action),

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

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

Multiple output policiesDavid Peterbefore adoption99d24b7

line 127why, one step back
127 output_policy,

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 128–135why, one step back
128 &command.get_command_line(),
129 )?;130131 Ok((132 TimingResult {133 time_real: result.time_real,134 time_user: result.time_user,135 time_system: result.time_system,

Initial work on tracking memory usageDavid Peterbefore adoption6556b2b

line 136why, one step back
136 memory_usage_byte: result.memory_usage_byte,

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 137–166why, one step back
137 },
138 result.status,139 ))140 }141142 fn calibrate(&mut self) -> Result<()> {143 Ok(())144 }145146 fn time_overhead(&self) -> Second {147 0.0148 }149}150151pub struct ShellExecutor<'a> {152 options: &'a Options,153 shell: &'a Shell,154 shell_spawning_time: Option<TimingResult>,155}156157impl<'a> ShellExecutor<'a> {158 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {159 ShellExecutor {160 shell,161 options,162 shell_spawning_time: None,163 }164 }165}166

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

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

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 168–170why, one step back
168 fn run_command_and_measure(
169 &self,170 command: &Command<'_>,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

Shrink unsafe blockcactterbefore adoption2e8ce30

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

Shrink unsafe blockcactterbefore adoption2e8ce30

line 174why, one step back
174 ) -> Result<(TimingResult, ExitStatus)> {

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

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

Shrink unsafe blockcactterbefore adoption2e8ce30

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

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

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

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

line 178why, one step back
178

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

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

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

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

fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5

lines 182–185why, one step back
182 command_builder.raw_arg(command.get_command_line());
183 } else {184 command_builder.arg(command.get_command_line());185 }

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 186–188why, one step back
186
187 let mut result = run_command_and_measure_common(188 command_builder,

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 189why, one step back
189 iteration,

Shrink unsafe blockcactterbefore adoption2e8ce30

line 190why, one step back
190 command_failure_action.unwrap_or(self.options.command_failure_action),

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

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

Multiple output policiesDavid Peterbefore adoption99d24b7

line 192why, one step back
192 output_policy,

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 193–207why, one step back
193 &command.get_command_line(),
194 )?;195196 // Subtract shell spawning time197 if let Some(spawning_time) = self.shell_spawning_time {198 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);199 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);200 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);201 }202203 Ok((204 TimingResult {205 time_real: result.time_real,206 time_user: result.time_user,207 time_system: result.time_system,

Initial work on tracking memory usageDavid Peterbefore adoption6556b2b

line 208why, one step back
208 memory_usage_byte: result.memory_usage_byte,

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 209–232why, one step back
209 },
210 result.status,211 ))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 };226227 let mut times_real: Vec<Second> = vec![];228 let mut times_user: Vec<Second> = vec![];229 let mut times_system: Vec<Second> = vec![];230231 for _ in 0..COUNT {232 // Just run the shell without any command

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

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

Multiple output policiesDavid Peterbefore adoption99d24b7

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

Add iteration information to failure error messageDavid Peterbefore adoption83f04cd

line 238why, one step back
238 );

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 239–272why, one step back
239
240 match res {241 Err(_) => {242 let shell_cmd = if cfg!(windows) {243 format!("{} /C \"\"", self.shell)244 } else {245 format!("{} -c \"\"", self.shell)246 };247248 bail!(249 "Could not measure shell execution time. Make sure you can run '{}'.",250 shell_cmd251 );252 }253 Ok((r, _)) => {254 times_real.push(r.time_real);255 times_user.push(r.time_user);256 times_system.push(r.time_system);257 }258 }259260 if let Some(bar) = progress_bar.as_ref() {261 bar.inc(1)262 }263 }264265 if let Some(bar) = progress_bar.as_ref() {266 bar.finish_and_clear()267 }268269 self.shell_spawning_time = Some(TimingResult {270 time_real: mean(&times_real),271 time_user: mean(&times_user),272 time_system: mean(&times_system),

Initial work on tracking memory usageDavid Peterbefore adoption6556b2b

line 273why, one step back
273 memory_usage_byte: 0,

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 274–307why, one step back
274 });
275276 Ok(())277 }278279 fn time_overhead(&self) -> Second {280 self.shell_spawning_time.unwrap().time_real281 }282}283284#[derive(Clone)]285pub struct MockExecutor {286 shell: Option<String>,287}288289impl MockExecutor {290 pub fn new(shell: Option<String>) -> Self {291 MockExecutor { shell }292 }293294 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {295 assert!(sleep_command.as_ref().starts_with("sleep "));296 sleep_command297 .as_ref()298 .trim_start_matches("sleep ")299 .parse::<Second>()300 .unwrap()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,

Shrink unsafe blockcactterbefore adoption2e8ce30

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,

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 311–328why, one step back
311 ) -> Result<(TimingResult, ExitStatus)> {
312 #[cfg(unix)]313 let status = {314 use std::os::unix::process::ExitStatusExt;315 ExitStatus::from_raw(0)316 };317318 #[cfg(windows)]319 let status = {320 use std::os::windows::process::ExitStatusExt;321 ExitStatus::from_raw(0)322 };323324 Ok((325 TimingResult {326 time_real: Self::extract_time(command.get_command_line()),327 time_user: 0.0,328 time_system: 0.0,

Initial work on tracking memory usageDavid Peterbefore adoption6556b2b

line 329why, one step back
329 memory_usage_byte: 0,

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 330–350why, one step back
330 },
331 status,332 ))333 }334335 fn calibrate(&mut self) -> Result<()> {336 Ok(())337 }338339 fn time_overhead(&self) -> Second {340 match &self.shell {341 None => 0.0,342 Some(shell) => Self::extract_time(shell),343 }344 }345}346347#[test]348fn test_mock_executor_extract_time() {349 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);350}