Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

293 lines · 8.5 KiB · Rust

Last changed by

Fixes #568FilipAnderssonbefore adoptionf00acf9

History of this file

Take it

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 1–3why, one step back
1use std::process::{ExitStatus, Stdio};
23use crate::command::Command;

Extract common functionalityDavid Peterbefore adoption308bf5c

line 4why, one step back
4use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};

Add debug/mock modeDavid Peterbefore adoption6f51232

line 5why, one step back
5use crate::output::progress_bar::get_progress_bar;

Extract common functionalityDavid Peterbefore adoption308bf5c

line 6why, one step back
6use crate::timer::{execute_and_measure, TimerResult};

Move custom functionality to executorDavid Peterbefore adoption1f3943e

line 7why, one step back
7use crate::util::randomized_environment_offset;

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 8–11why, one step back
8use crate::util::units::Second;
910use super::timing_result::TimingResult;11

Further simplify execute_and_measureDavid Peterbefore adoptione1da8ba

line 12why, one step back
12use anyhow::{bail, Context, Result};

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 13–15why, one step back
13use statistical::mean;
1415pub trait Executor {

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

lines 16–17why, one step back
16 /// Run the given command and measure the execution time
17 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 18–22why, one step back
18 &self,
19 command: &Command<'_>,20 command_failure_action: Option<CmdFailureAction>,21 ) -> Result<(TimingResult, ExitStatus)>;22

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

lines 23–26why, one step back
23 /// Perform a calibration of this executor. For example,
24 /// when running commands through a shell, we need to25 /// measure the shell spawning time separately in order26 /// to subtract it from the full runtime later.

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 27–28why, one step back
27 fn calibrate(&mut self) -> Result<()>;
28

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

lines 29–32why, one step back
29 /// Return the time overhead for this executor when
30 /// performing a measurement. This should return the time31 /// that is being used in addition to the actual runtime32 /// of the command.

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 33–35why, one step back
33 fn time_overhead(&self) -> Second;
34}35

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 36–38why, one step back
36fn run_command_and_measure_common(
37 mut command: std::process::Command,38 command_failure_action: CmdFailureAction,

Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c

line 39why, one step back
39 command_output_policy: &CommandOutputPolicy,

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 40–41why, one step back
40 command_name: &str,
41) -> Result<TimerResult> {

Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c

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

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 43–66why, one step back
43 command.stdin(Stdio::null()).stdout(stdout).stderr(stderr);
4445 command.env(46 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",47 randomized_environment_offset::value(),48 );4950 let result = execute_and_measure(command)51 .with_context(|| format!("Failed to run command '{}'", command_name))?;5253 if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {54 bail!(55 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \56 Alternatively, use the '--show-output' option to debug what went wrong.",57 result.status.code().map_or(58 "The process has been terminated by a signal".into(),59 |c| format!("Command terminated with non-zero exit code: {}", c)60 )61 );62 }6364 Ok(result)65}66

Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0

lines 67–85why, one step back
67pub struct RawExecutor<'a> {
68 options: &'a Options,69}7071impl<'a> RawExecutor<'a> {72 pub fn new(options: &'a Options) -> Self {73 RawExecutor { options }74 }75}7677impl<'a> Executor for RawExecutor<'a> {78 fn run_command_and_measure(79 &self,80 command: &Command<'_>,81 command_failure_action: Option<CmdFailureAction>,82 ) -> Result<(TimingResult, ExitStatus)> {83 let result = run_command_and_measure_common(84 command.get_command()?,85 command_failure_action.unwrap_or(self.options.command_failure_action),

Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c

line 86why, one step back
86 &self.options.command_output_policy,

Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0

lines 87–108why, one step back
87 &command.get_command_line(),
88 )?;8990 Ok((91 TimingResult {92 time_real: result.time_real,93 time_user: result.time_user,94 time_system: result.time_system,95 },96 result.status,97 ))98 }99100 fn calibrate(&mut self) -> Result<()> {101 Ok(())102 }103104 fn time_overhead(&self) -> Second {105 0.0106 }107}108

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 109–125why, one step back
109pub struct ShellExecutor<'a> {
110 options: &'a Options,111 shell: &'a Shell,112 shell_spawning_time: Option<TimingResult>,113}114115impl<'a> ShellExecutor<'a> {116 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {117 ShellExecutor {118 shell,119 options,120 shell_spawning_time: None,121 }122 }123}124125impl<'a> Executor for ShellExecutor<'a> {

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 126why, one step back
126 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 127–130why, one step back
127 &self,
128 command: &Command<'_>,129 command_failure_action: Option<CmdFailureAction>,130 ) -> Result<(TimingResult, ExitStatus)> {

Move custom functionality to executorDavid Peterbefore adoption1f3943e

lines 131–132why, one step back
131 let mut command_builder = self.shell.command();
132 command_builder

Fixes #568FilipAnderssonbefore adoptionf00acf9

lines 133–139why, one step back
133 .arg(
134 if cfg!(windows) && *self.shell == Shell::Default("cmd.exe") {135 "/C"136 } else {137 "-c"138 },139 )

Change argument orderDavid Peterbefore adoptione001530

line 140why, one step back
140 .arg(command.get_command_line());

Move custom functionality to executorDavid Peterbefore adoption1f3943e

line 141why, one step back
141

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 142–144why, one step back
142 let mut result = run_command_and_measure_common(
143 command_builder,144 command_failure_action.unwrap_or(self.options.command_failure_action),

Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c

line 145why, one step back
145 &self.options.command_output_policy,

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 146–147why, one step back
146 &command.get_command_line(),
147 )?;

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 148–150why, one step back
148
149 // Subtract shell spawning time150 if let Some(spawning_time) = self.shell_spawning_time {

SimplifyDavid Peterbefore adoptionf19223b

lines 151–153why, one step back
151 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);
152 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);153 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 154–157why, one step back
154 }
155156 Ok((157 TimingResult {

SimplifyDavid Peterbefore adoptionf19223b

lines 158–160why, one step back
158 time_real: result.time_real,
159 time_user: result.time_user,160 time_system: result.time_system,

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 161–184why, one step back
161 },
162 result.status,163 ))164 }165166 /// Measure the average shell spawning time167 fn calibrate(&mut self) -> Result<()> {168 const COUNT: u64 = 50;169 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {170 Some(get_progress_bar(171 COUNT,172 "Measuring shell spawning time",173 self.options.output_style,174 ))175 } else {176 None177 };178179 let mut times_real: Vec<Second> = vec![];180 let mut times_user: Vec<Second> = vec![];181 let mut times_system: Vec<Second> = vec![];182183 for _ in 0..COUNT {184 // Just run the shell without any command

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 185why, one step back
185 let res = self.run_command_and_measure(&Command::new(None, ""), None);

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 186–230why, one step back
186
187 match res {188 Err(_) => {189 let shell_cmd = if cfg!(windows) {190 format!("{} /C \"\"", self.shell)191 } else {192 format!("{} -c \"\"", self.shell)193 };194195 bail!(196 "Could not measure shell execution time. Make sure you can run '{}'.",197 shell_cmd198 );199 }200 Ok((r, _)) => {201 times_real.push(r.time_real);202 times_user.push(r.time_user);203 times_system.push(r.time_system);204 }205 }206207 if let Some(bar) = progress_bar.as_ref() {208 bar.inc(1)209 }210 }211212 if let Some(bar) = progress_bar.as_ref() {213 bar.finish_and_clear()214 }215216 self.shell_spawning_time = Some(TimingResult {217 time_real: mean(&times_real),218 time_user: mean(&times_user),219 time_system: mean(&times_system),220 });221222 Ok(())223 }224225 fn time_overhead(&self) -> Second {226 self.shell_spawning_time.unwrap().time_real227 }228}229230#[derive(Clone)]

Proper shell overhead computationDavid Peterbefore adoption6887835

lines 231–232why, one step back
231pub struct MockExecutor {
232 shell: Option<String>,

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Proper shell overhead computationDavid Peterbefore adoption6887835

lines 235–236why, one step back
235impl MockExecutor {
236 pub fn new(shell: Option<String>) -> Self {

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 237–249why, one step back
237 MockExecutor { shell }
238 }239240 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {241 assert!(sleep_command.as_ref().starts_with("sleep "));242 sleep_command243 .as_ref()244 .trim_start_matches("sleep ")245 .parse::<Second>()246 .unwrap()247 }248}249

Proper shell overhead computationDavid Peterbefore adoption6887835

line 250why, one step back
250impl Executor for MockExecutor {

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 251why, one step back
251 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 252–269why, one step back
252 &self,
253 command: &Command<'_>,254 _command_failure_action: Option<CmdFailureAction>,255 ) -> Result<(TimingResult, ExitStatus)> {256 #[cfg(unix)]257 let status = {258 use std::os::unix::process::ExitStatusExt;259 ExitStatus::from_raw(0)260 };261262 #[cfg(windows)]263 let status = {264 use std::os::windows::process::ExitStatusExt;265 ExitStatus::from_raw(0)266 };267268 Ok((269 TimingResult {

Rename to get_command_lineDavid Peterbefore adoption826449b

line 270why, one step back
270 time_real: Self::extract_time(command.get_command_line()),

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 271–282why, one step back
271 time_user: 0.0,
272 time_system: 0.0,273 },274 status,275 ))276 }277278 fn calibrate(&mut self) -> Result<()> {279 Ok(())280 }281282 fn time_overhead(&self) -> Second {

Proper shell overhead computationDavid Peterbefore adoption6887835

lines 283–285why, one step back
283 match &self.shell {
284 None => 0.0,285 Some(shell) => Self::extract_time(shell),

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 286–293why, one step back
286 }
287 }288}289290#[test]291fn test_mock_executor_extract_time() {292 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);293}