Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

287 lines · 8.3 KiB · Rust

Last changed by

Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0

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–66why, one step back
36fn run_command_and_measure_common(
37 mut command: std::process::Command,38 command_failure_action: CmdFailureAction,39 command_output_policy: CommandOutputPolicy,40 command_name: &str,41) -> Result<TimerResult> {42 let (stdout, stderr) = command_output_policy.get_stdout_stderr();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–108why, 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),86 self.options.command_output_policy,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

Change argument orderDavid Peterbefore adoptione001530

lines 133–134why, one step back
133 .arg(if cfg!(windows) { "/C" } else { "-c" })
134 .arg(command.get_command_line());

Move custom functionality to executorDavid Peterbefore adoption1f3943e

line 135why, one step back
135

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 136–141why, one step back
136 let mut result = run_command_and_measure_common(
137 command_builder,138 command_failure_action.unwrap_or(self.options.command_failure_action),139 self.options.command_output_policy,140 &command.get_command_line(),141 )?;

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 142–144why, one step back
142
143 // Subtract shell spawning time144 if let Some(spawning_time) = self.shell_spawning_time {

SimplifyDavid Peterbefore adoptionf19223b

lines 145–147why, one step back
145 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);
146 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);147 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 148–151why, one step back
148 }
149150 Ok((151 TimingResult {

SimplifyDavid Peterbefore adoptionf19223b

lines 152–154why, one step back
152 time_real: result.time_real,
153 time_user: result.time_user,154 time_system: result.time_system,

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 155–178why, one step back
155 },
156 result.status,157 ))158 }159160 /// Measure the average shell spawning time161 fn calibrate(&mut self) -> Result<()> {162 const COUNT: u64 = 50;163 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {164 Some(get_progress_bar(165 COUNT,166 "Measuring shell spawning time",167 self.options.output_style,168 ))169 } else {170 None171 };172173 let mut times_real: Vec<Second> = vec![];174 let mut times_user: Vec<Second> = vec![];175 let mut times_system: Vec<Second> = vec![];176177 for _ in 0..COUNT {178 // Just run the shell without any command

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 180–224why, one step back
180
181 match res {182 Err(_) => {183 let shell_cmd = if cfg!(windows) {184 format!("{} /C \"\"", self.shell)185 } else {186 format!("{} -c \"\"", self.shell)187 };188189 bail!(190 "Could not measure shell execution time. Make sure you can run '{}'.",191 shell_cmd192 );193 }194 Ok((r, _)) => {195 times_real.push(r.time_real);196 times_user.push(r.time_user);197 times_system.push(r.time_system);198 }199 }200201 if let Some(bar) = progress_bar.as_ref() {202 bar.inc(1)203 }204 }205206 if let Some(bar) = progress_bar.as_ref() {207 bar.finish_and_clear()208 }209210 self.shell_spawning_time = Some(TimingResult {211 time_real: mean(&times_real),212 time_user: mean(&times_user),213 time_system: mean(&times_system),214 });215216 Ok(())217 }218219 fn time_overhead(&self) -> Second {220 self.shell_spawning_time.unwrap().time_real221 }222}223224#[derive(Clone)]

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 227–228why, one step back
227}
228

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 231–243why, one step back
231 MockExecutor { shell }
232 }233234 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {235 assert!(sleep_command.as_ref().starts_with("sleep "));236 sleep_command237 .as_ref()238 .trim_start_matches("sleep ")239 .parse::<Second>()240 .unwrap()241 }242}243

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 245why, one step back
245 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 246–263why, one step back
246 &self,
247 command: &Command<'_>,248 _command_failure_action: Option<CmdFailureAction>,249 ) -> Result<(TimingResult, ExitStatus)> {250 #[cfg(unix)]251 let status = {252 use std::os::unix::process::ExitStatusExt;253 ExitStatus::from_raw(0)254 };255256 #[cfg(windows)]257 let status = {258 use std::os::windows::process::ExitStatusExt;259 ExitStatus::from_raw(0)260 };261262 Ok((263 TimingResult {

Rename to get_command_lineDavid Peterbefore adoption826449b

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 265–276why, one step back
265 time_user: 0.0,
266 time_system: 0.0,267 },268 status,269 ))270 }271272 fn calibrate(&mut self) -> Result<()> {273 Ok(())274 }275276 fn time_overhead(&self) -> Second {

Proper shell overhead computationDavid Peterbefore adoption6887835

lines 277–279why, one step back
277 match &self.shell {
278 None => 0.0,279 Some(shell) => Self::extract_time(shell),

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 280–287why, one step back
280 }
281 }282}283284#[test]285fn test_mock_executor_extract_time() {286 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);287}