Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

297 lines · 8.7 KiB · Rust

Last changed by

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

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;

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

line 4why, one step back
4use crate::options::{CmdFailureAction, CommandInputPolicy, 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,

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

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

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

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

Extract common functionalityDavid Peterbefore adoption308bf5c

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

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

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

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

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

Extract common functionalityDavid Peterbefore adoption308bf5c

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

Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0

lines 69–87why, one step back
69pub struct RawExecutor<'a> {
70 options: &'a Options,71}7273impl<'a> RawExecutor<'a> {74 pub fn new(options: &'a Options) -> Self {75 RawExecutor { options }76 }77}7879impl<'a> Executor for RawExecutor<'a> {80 fn run_command_and_measure(81 &self,82 command: &Command<'_>,83 command_failure_action: Option<CmdFailureAction>,84 ) -> Result<(TimingResult, ExitStatus)> {85 let result = run_command_and_measure_common(86 command.get_command()?,87 command_failure_action.unwrap_or(self.options.command_failure_action),

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

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

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

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

Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0

lines 90–111why, one step back
90 &command.get_command_line(),
91 )?;9293 Ok((94 TimingResult {95 time_real: result.time_real,96 time_user: result.time_user,97 time_system: result.time_system,98 },99 result.status,100 ))101 }102103 fn calibrate(&mut self) -> Result<()> {104 Ok(())105 }106107 fn time_overhead(&self) -> Second {108 0.0109 }110}111

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 112–128why, one step back
112pub struct ShellExecutor<'a> {
113 options: &'a Options,114 shell: &'a Shell,115 shell_spawning_time: Option<TimingResult>,116}117118impl<'a> ShellExecutor<'a> {119 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {120 ShellExecutor {121 shell,122 options,123 shell_spawning_time: None,124 }125 }126}127128impl<'a> Executor for ShellExecutor<'a> {

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 129why, one step back
129 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Move custom functionality to executorDavid Peterbefore adoption1f3943e

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

Fixes #568FilipAnderssonbefore adoptionf00acf9

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

Change argument orderDavid Peterbefore adoptione001530

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

Move custom functionality to executorDavid Peterbefore adoption1f3943e

line 144why, one step back
144

Extract common functionalityDavid Peterbefore adoption308bf5c

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

Added --stdin-data argumentSteve Neasebefore adoptione38acdb

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

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

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

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 150–151why, one step back
150 &command.get_command_line(),
151 )?;

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 152–154why, one step back
152
153 // Subtract shell spawning time154 if let Some(spawning_time) = self.shell_spawning_time {

SimplifyDavid Peterbefore adoptionf19223b

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 158–161why, one step back
158 }
159160 Ok((161 TimingResult {

SimplifyDavid Peterbefore adoptionf19223b

lines 162–164why, one step back
162 time_real: result.time_real,
163 time_user: result.time_user,164 time_system: result.time_system,

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 165–188why, one step back
165 },
166 result.status,167 ))168 }169170 /// Measure the average shell spawning time171 fn calibrate(&mut self) -> Result<()> {172 const COUNT: u64 = 50;173 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {174 Some(get_progress_bar(175 COUNT,176 "Measuring shell spawning time",177 self.options.output_style,178 ))179 } else {180 None181 };182183 let mut times_real: Vec<Second> = vec![];184 let mut times_user: Vec<Second> = vec![];185 let mut times_system: Vec<Second> = vec![];186187 for _ in 0..COUNT {188 // Just run the shell without any command

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 190–234why, one step back
190
191 match res {192 Err(_) => {193 let shell_cmd = if cfg!(windows) {194 format!("{} /C \"\"", self.shell)195 } else {196 format!("{} -c \"\"", self.shell)197 };198199 bail!(200 "Could not measure shell execution time. Make sure you can run '{}'.",201 shell_cmd202 );203 }204 Ok((r, _)) => {205 times_real.push(r.time_real);206 times_user.push(r.time_user);207 times_system.push(r.time_system);208 }209 }210211 if let Some(bar) = progress_bar.as_ref() {212 bar.inc(1)213 }214 }215216 if let Some(bar) = progress_bar.as_ref() {217 bar.finish_and_clear()218 }219220 self.shell_spawning_time = Some(TimingResult {221 time_real: mean(&times_real),222 time_user: mean(&times_user),223 time_system: mean(&times_system),224 });225226 Ok(())227 }228229 fn time_overhead(&self) -> Second {230 self.shell_spawning_time.unwrap().time_real231 }232}233234#[derive(Clone)]

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 237–238why, one step back
237}
238

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 241–253why, one step back
241 MockExecutor { shell }
242 }243244 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {245 assert!(sleep_command.as_ref().starts_with("sleep "));246 sleep_command247 .as_ref()248 .trim_start_matches("sleep ")249 .parse::<Second>()250 .unwrap()251 }252}253

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 255why, one step back
255 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 256–273why, one step back
256 &self,
257 command: &Command<'_>,258 _command_failure_action: Option<CmdFailureAction>,259 ) -> Result<(TimingResult, ExitStatus)> {260 #[cfg(unix)]261 let status = {262 use std::os::unix::process::ExitStatusExt;263 ExitStatus::from_raw(0)264 };265266 #[cfg(windows)]267 let status = {268 use std::os::windows::process::ExitStatusExt;269 ExitStatus::from_raw(0)270 };271272 Ok((273 TimingResult {

Rename to get_command_lineDavid Peterbefore adoption826449b

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 275–286why, one step back
275 time_user: 0.0,
276 time_system: 0.0,277 },278 status,279 ))280 }281282 fn calibrate(&mut self) -> Result<()> {283 Ok(())284 }285286 fn time_overhead(&self) -> Second {

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 290–297why, one step back
290 }
291 }292}293294#[test]295fn test_mock_executor_extract_time() {296 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);297}