Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

299 lines · 8.7 KiB · Rust

Last changed by

ran cargo fmtSteve Neasebefore adoption0e3bad1

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;

ran cargo fmtSteve Neasebefore adoption0e3bad1

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

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Extract common functionalityDavid Peterbefore adoption308bf5c

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

Move custom functionality to executorDavid Peterbefore adoption1f3943e

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 10–13why, one step back
10use crate::util::units::Second;
1112use super::timing_result::TimingResult;13

Further simplify execute_and_measureDavid Peterbefore adoptione1da8ba

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

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

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

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

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

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

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

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Extract common functionalityDavid Peterbefore adoption308bf5c

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

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

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

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

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

Extract common functionalityDavid Peterbefore adoption308bf5c

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

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

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

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

lines 46–47why, one step back
46 let stdin = command_input_policy.get_stdin()?;
47 command.stdin(stdin).stdout(stdout).stderr(stderr);

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 48–70why, one step back
48
49 command.env(50 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",51 randomized_environment_offset::value(),52 );5354 let result = execute_and_measure(command)55 .with_context(|| format!("Failed to run command '{}'", command_name))?;5657 if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {58 bail!(59 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \60 Alternatively, use the '--show-output' option to debug what went wrong.",61 result.status.code().map_or(62 "The process has been terminated by a signal".into(),63 |c| format!("Command terminated with non-zero exit code: {}", c)64 )65 );66 }6768 Ok(result)69}70

Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0

lines 71–89why, one step back
71pub struct RawExecutor<'a> {
72 options: &'a Options,73}7475impl<'a> RawExecutor<'a> {76 pub fn new(options: &'a Options) -> Self {77 RawExecutor { options }78 }79}8081impl<'a> Executor for RawExecutor<'a> {82 fn run_command_and_measure(83 &self,84 command: &Command<'_>,85 command_failure_action: Option<CmdFailureAction>,86 ) -> Result<(TimingResult, ExitStatus)> {87 let result = run_command_and_measure_common(88 command.get_command()?,89 command_failure_action.unwrap_or(self.options.command_failure_action),

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

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

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

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

Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0

lines 92–113why, one step back
92 &command.get_command_line(),
93 )?;9495 Ok((96 TimingResult {97 time_real: result.time_real,98 time_user: result.time_user,99 time_system: result.time_system,100 },101 result.status,102 ))103 }104105 fn calibrate(&mut self) -> Result<()> {106 Ok(())107 }108109 fn time_overhead(&self) -> Second {110 0.0111 }112}113

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 114–130why, one step back
114pub struct ShellExecutor<'a> {
115 options: &'a Options,116 shell: &'a Shell,117 shell_spawning_time: Option<TimingResult>,118}119120impl<'a> ShellExecutor<'a> {121 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {122 ShellExecutor {123 shell,124 options,125 shell_spawning_time: None,126 }127 }128}129130impl<'a> Executor for ShellExecutor<'a> {

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 131why, one step back
131 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 132–135why, one step back
132 &self,
133 command: &Command<'_>,134 command_failure_action: Option<CmdFailureAction>,135 ) -> Result<(TimingResult, ExitStatus)> {

Move custom functionality to executorDavid Peterbefore adoption1f3943e

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

Fixes #568FilipAnderssonbefore adoptionf00acf9

lines 138–144why, one step back
138 .arg(
139 if cfg!(windows) && *self.shell == Shell::Default("cmd.exe") {140 "/C"141 } else {142 "-c"143 },144 )

Change argument orderDavid Peterbefore adoptione001530

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

Move custom functionality to executorDavid Peterbefore adoption1f3943e

line 146why, one step back
146

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 147–149why, one step back
147 let mut result = run_command_and_measure_common(
148 command_builder,149 command_failure_action.unwrap_or(self.options.command_failure_action),

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

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

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

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

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 152–153why, one step back
152 &command.get_command_line(),
153 )?;

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 154–156why, one step back
154
155 // Subtract shell spawning time156 if let Some(spawning_time) = self.shell_spawning_time {

SimplifyDavid Peterbefore adoptionf19223b

lines 157–159why, one step back
157 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);
158 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);159 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 160–163why, one step back
160 }
161162 Ok((163 TimingResult {

SimplifyDavid Peterbefore adoptionf19223b

lines 164–166why, one step back
164 time_real: result.time_real,
165 time_user: result.time_user,166 time_system: result.time_system,

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 167–190why, one step back
167 },
168 result.status,169 ))170 }171172 /// Measure the average shell spawning time173 fn calibrate(&mut self) -> Result<()> {174 const COUNT: u64 = 50;175 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {176 Some(get_progress_bar(177 COUNT,178 "Measuring shell spawning time",179 self.options.output_style,180 ))181 } else {182 None183 };184185 let mut times_real: Vec<Second> = vec![];186 let mut times_user: Vec<Second> = vec![];187 let mut times_system: Vec<Second> = vec![];188189 for _ in 0..COUNT {190 // Just run the shell without any command

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 192–236why, one step back
192
193 match res {194 Err(_) => {195 let shell_cmd = if cfg!(windows) {196 format!("{} /C \"\"", self.shell)197 } else {198 format!("{} -c \"\"", self.shell)199 };200201 bail!(202 "Could not measure shell execution time. Make sure you can run '{}'.",203 shell_cmd204 );205 }206 Ok((r, _)) => {207 times_real.push(r.time_real);208 times_user.push(r.time_user);209 times_system.push(r.time_system);210 }211 }212213 if let Some(bar) = progress_bar.as_ref() {214 bar.inc(1)215 }216 }217218 if let Some(bar) = progress_bar.as_ref() {219 bar.finish_and_clear()220 }221222 self.shell_spawning_time = Some(TimingResult {223 time_real: mean(&times_real),224 time_user: mean(&times_user),225 time_system: mean(&times_system),226 });227228 Ok(())229 }230231 fn time_overhead(&self) -> Second {232 self.shell_spawning_time.unwrap().time_real233 }234}235236#[derive(Clone)]

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 239–240why, one step back
239}
240

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 243–255why, one step back
243 MockExecutor { shell }
244 }245246 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {247 assert!(sleep_command.as_ref().starts_with("sleep "));248 sleep_command249 .as_ref()250 .trim_start_matches("sleep ")251 .parse::<Second>()252 .unwrap()253 }254}255

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 257why, one step back
257 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 258–275why, one step back
258 &self,
259 command: &Command<'_>,260 _command_failure_action: Option<CmdFailureAction>,261 ) -> Result<(TimingResult, ExitStatus)> {262 #[cfg(unix)]263 let status = {264 use std::os::unix::process::ExitStatusExt;265 ExitStatus::from_raw(0)266 };267268 #[cfg(windows)]269 let status = {270 use std::os::windows::process::ExitStatusExt;271 ExitStatus::from_raw(0)272 };273274 Ok((275 TimingResult {

Rename to get_command_lineDavid Peterbefore adoption826449b

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 277–288why, one step back
277 time_user: 0.0,
278 time_system: 0.0,279 },280 status,281 ))282 }283284 fn calibrate(&mut self) -> Result<()> {285 Ok(())286 }287288 fn time_overhead(&self) -> Second {

Proper shell overhead computationDavid Peterbefore adoption6887835

lines 289–291why, one step back
289 match &self.shell {
290 None => 0.0,291 Some(shell) => Self::extract_time(shell),

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 292–299why, one step back
292 }
293 }294}295296#[test]297fn test_mock_executor_extract_time() {298 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);299}