executor.rs
This file
Path
src/benchmark/executor.rs
287 lines · 8.4 KiB · Rust
Last changed by
Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c
History of this fileTake it
Add debug/mock modeDavid Peterbefore adoption6f51232
lines 1–3why, one step back1use std::process::{ExitStatus, Stdio};23use crate::command::Command;Extract common functionalityDavid Peterbefore adoption308bf5c
line 4why, one step back4use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};Add debug/mock modeDavid Peterbefore adoption6f51232
line 5why, one step back5use crate::output::progress_bar::get_progress_bar;Extract common functionalityDavid Peterbefore adoption308bf5c
line 6why, one step back6use crate::timer::{execute_and_measure, TimerResult};Move custom functionality to executorDavid Peterbefore adoption1f3943e
line 7why, one step back7use crate::util::randomized_environment_offset;Add debug/mock modeDavid Peterbefore adoption6f51232
lines 8–11why, one step back8use crate::util::units::Second;910use super::timing_result::TimingResult;11Further simplify execute_and_measureDavid Peterbefore adoptione1da8ba
line 12why, one step back12use anyhow::{bail, Context, Result};Add debug/mock modeDavid Peterbefore adoption6f51232
lines 13–15why, one step back13use statistical::mean;1415pub trait Executor {Rename to run_command_and_measureDavid Peterbefore adoption7c929f7
lines 16–17why, one step back16 /// Run the given command and measure the execution time17 fn run_command_and_measure(Add debug/mock modeDavid Peterbefore adoption6f51232
lines 18–22why, one step back18 &self,19 command: &Command<'_>,20 command_failure_action: Option<CmdFailureAction>,21 ) -> Result<(TimingResult, ExitStatus)>;22Rename to run_command_and_measureDavid Peterbefore adoption7c929f7
lines 23–26why, one step back23 /// 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 back27 fn calibrate(&mut self) -> Result<()>;28Rename to run_command_and_measureDavid Peterbefore adoption7c929f7
lines 29–32why, one step back29 /// Return the time overhead for this executor when30 /// 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 back33 fn time_overhead(&self) -> Second;34}35Extract common functionalityDavid Peterbefore adoption308bf5c
lines 36–38why, one step back36fn 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 back39 command_output_policy: &CommandOutputPolicy,Extract common functionalityDavid Peterbefore adoption308bf5c
lines 40–41why, one step back40 command_name: &str,41) -> Result<TimerResult> {Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c
line 42why, one step back42 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;Extract common functionalityDavid Peterbefore adoption308bf5c
lines 43–66why, one step back43 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}66Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0
lines 67–85why, one step back67pub 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 back86 &self.options.command_output_policy,Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0
lines 87–108why, one step back87 &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}108Add debug/mock modeDavid Peterbefore adoption6f51232
lines 109–125why, one step back109pub 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 back126 fn run_command_and_measure(Add debug/mock modeDavid Peterbefore adoption6f51232
lines 127–130why, one step back127 &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 back131 let mut command_builder = self.shell.command();132 command_builderChange argument orderDavid Peterbefore adoptione001530
lines 133–134why, one step back133 .arg(if cfg!(windows) { "/C" } else { "-c" })134 .arg(command.get_command_line());Move custom functionality to executorDavid Peterbefore adoption1f3943e
line 135why, one step back135Extract common functionalityDavid Peterbefore adoption308bf5c
lines 136–138why, one step back136 let mut result = run_command_and_measure_common(137 command_builder,138 command_failure_action.unwrap_or(self.options.command_failure_action),Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c
line 139why, one step back139 &self.options.command_output_policy,Extract common functionalityDavid Peterbefore adoption308bf5c
lines 140–141why, one step back140 &command.get_command_line(),141 )?;Add debug/mock modeDavid Peterbefore adoption6f51232
lines 142–144why, one step back142143 // Subtract shell spawning time144 if let Some(spawning_time) = self.shell_spawning_time {SimplifyDavid Peterbefore adoptionf19223b
lines 145–147why, one step back145 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 back148 }149150 Ok((151 TimingResult {SimplifyDavid Peterbefore adoptionf19223b
lines 152–154why, one step back152 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 back155 },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 commandRename to run_command_and_measureDavid Peterbefore adoption7c929f7
line 179why, one step back179 let res = self.run_command_and_measure(&Command::new(None, ""), None);Add debug/mock modeDavid Peterbefore adoption6f51232
lines 180–224why, one step back180181 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(×_real),212 time_user: mean(×_user),213 time_system: mean(×_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 back225pub struct MockExecutor {226 shell: Option<String>,Add debug/mock modeDavid Peterbefore adoption6f51232
lines 227–228why, one step back227}228Proper shell overhead computationDavid Peterbefore adoption6887835
lines 229–230why, one step back229impl MockExecutor {230 pub fn new(shell: Option<String>) -> Self {Add debug/mock modeDavid Peterbefore adoption6f51232
lines 231–243why, one step back231 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}243Proper shell overhead computationDavid Peterbefore adoption6887835
line 244why, one step back244impl Executor for MockExecutor {Rename to run_command_and_measureDavid Peterbefore adoption7c929f7
line 245why, one step back245 fn run_command_and_measure(Add debug/mock modeDavid Peterbefore adoption6f51232
lines 246–263why, one step back246 &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 back264 time_real: Self::extract_time(command.get_command_line()),Add debug/mock modeDavid Peterbefore adoption6f51232
lines 265–276why, one step back265 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 back277 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 back280 }281 }282}283284#[test]285fn test_mock_executor_extract_time() {286 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);287}