executor.rs
This file
Path
src/benchmark/executor.rs
246 lines · 7.3 KiB · Rust
Last changed by
Move wall clock timer into execute_and_measureDavid Peterbefore adoption55f0ef6
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;Move Stdio extraction to enumDavid Peterbefore adoption9b8f2a9
line 4why, one step back4use crate::options::{CmdFailureAction, Options, OutputStyleOption, Shell};Add debug/mock modeDavid Peterbefore adoption6f51232
line 5why, one step back5use crate::output::progress_bar::get_progress_bar;Move wall clock timer into execute_and_measureDavid Peterbefore adoption55f0ef6
line 6why, one step back6use crate::timer::execute_and_measure;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–60why, one step back33 fn time_overhead(&self) -> Second;34}3536pub struct ShellExecutor<'a> {37 options: &'a Options,38 shell: &'a Shell,39 shell_spawning_time: Option<TimingResult>,40}4142impl<'a> ShellExecutor<'a> {43 fn subtract_shell_spawning_time(&self, time: Second, shell_spawning_time: Second) -> Second {44 if time < shell_spawning_time {45 0.046 } else {47 time - shell_spawning_time48 }49 }5051 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {52 ShellExecutor {53 shell,54 options,55 shell_spawning_time: None,56 }57 }58}5960impl<'a> Executor for ShellExecutor<'a> {Rename to run_command_and_measureDavid Peterbefore adoption7c929f7
line 61why, one step back61 fn run_command_and_measure(Add debug/mock modeDavid Peterbefore adoption6f51232
lines 62–65why, one step back62 &self,63 command: &Command<'_>,64 command_failure_action: Option<CmdFailureAction>,65 ) -> Result<(TimingResult, ExitStatus)> {Move Stdio extraction to enumDavid Peterbefore adoption9b8f2a9
line 66why, one step back66 let (stdout, stderr) = self.options.command_output_policy.get_stdout_stderr();Add debug/mock modeDavid Peterbefore adoption6f51232
line 67why, one step back67Move custom functionality to executorDavid Peterbefore adoption1f3943e
lines 68–69why, one step back68 let mut command_builder = self.shell.command();69 command_builderChange argument orderDavid Peterbefore adoptione001530
lines 70–72why, one step back70 .stdin(Stdio::null())71 .stdout(stdout)72 .stderr(stderr)Move custom functionality to executorDavid Peterbefore adoption1f3943e
lines 73–76why, one step back73 .env(74 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",75 randomized_environment_offset::value(),76 )Change argument orderDavid Peterbefore adoptione001530
lines 77–78why, one step back77 .arg(if cfg!(windows) { "/C" } else { "-c" })78 .arg(command.get_command_line());Move custom functionality to executorDavid Peterbefore adoption1f3943e
line 79why, one step back79Further simplify execute_and_measureDavid Peterbefore adoptione1da8ba
lines 80–81why, one step back80 let result = execute_and_measure(command_builder)81 .with_context(|| format!("Failed to run command '{}'", command.get_command_line()))?;Add debug/mock modeDavid Peterbefore adoption6f51232
line 82why, one step back82Move wall clock timer into execute_and_measureDavid Peterbefore adoption55f0ef6
lines 83–86why, one step back83 let mut time_real = result.time_real;8485 let mut time_user = result.time_user;86 let mut time_system = result.time_system;Add debug/mock modeDavid Peterbefore adoption6f51232
lines 87–137why, one step back8788 if command_failure_action.unwrap_or(self.options.command_failure_action)89 == CmdFailureAction::RaiseError90 && !result.status.success()91 {92 bail!(93 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \94 Alternatively, use the '--show-output' option to debug what went wrong.",95 result.status.code().map_or(96 "The process has been terminated by a signal".into(),97 |c| format!("Command terminated with non-zero exit code: {}", c)98 )99 );100 }101102 // Subtract shell spawning time103 if let Some(spawning_time) = self.shell_spawning_time {104 time_real = self.subtract_shell_spawning_time(time_real, spawning_time.time_real);105 time_user = self.subtract_shell_spawning_time(time_user, spawning_time.time_user);106 time_system = self.subtract_shell_spawning_time(time_system, spawning_time.time_system);107 }108109 Ok((110 TimingResult {111 time_real,112 time_user,113 time_system,114 },115 result.status,116 ))117 }118119 /// Measure the average shell spawning time120 fn calibrate(&mut self) -> Result<()> {121 const COUNT: u64 = 50;122 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {123 Some(get_progress_bar(124 COUNT,125 "Measuring shell spawning time",126 self.options.output_style,127 ))128 } else {129 None130 };131132 let mut times_real: Vec<Second> = vec![];133 let mut times_user: Vec<Second> = vec![];134 let mut times_system: Vec<Second> = vec![];135136 for _ in 0..COUNT {137 // Just run the shell without any commandRename to run_command_and_measureDavid Peterbefore adoption7c929f7
line 138why, one step back138 let res = self.run_command_and_measure(&Command::new(None, ""), None);Add debug/mock modeDavid Peterbefore adoption6f51232
lines 139–183why, one step back139140 match res {141 Err(_) => {142 let shell_cmd = if cfg!(windows) {143 format!("{} /C \"\"", self.shell)144 } else {145 format!("{} -c \"\"", self.shell)146 };147148 bail!(149 "Could not measure shell execution time. Make sure you can run '{}'.",150 shell_cmd151 );152 }153 Ok((r, _)) => {154 times_real.push(r.time_real);155 times_user.push(r.time_user);156 times_system.push(r.time_system);157 }158 }159160 if let Some(bar) = progress_bar.as_ref() {161 bar.inc(1)162 }163 }164165 if let Some(bar) = progress_bar.as_ref() {166 bar.finish_and_clear()167 }168169 self.shell_spawning_time = Some(TimingResult {170 time_real: mean(×_real),171 time_user: mean(×_user),172 time_system: mean(×_system),173 });174175 Ok(())176 }177178 fn time_overhead(&self) -> Second {179 self.shell_spawning_time.unwrap().time_real180 }181}182183#[derive(Clone)]Proper shell overhead computationDavid Peterbefore adoption6887835
lines 184–185why, one step back184pub struct MockExecutor {185 shell: Option<String>,Add debug/mock modeDavid Peterbefore adoption6f51232
lines 186–187why, one step back186}187Proper shell overhead computationDavid Peterbefore adoption6887835
lines 188–189why, one step back188impl MockExecutor {189 pub fn new(shell: Option<String>) -> Self {Add debug/mock modeDavid Peterbefore adoption6f51232
lines 190–202why, one step back190 MockExecutor { shell }191 }192193 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {194 assert!(sleep_command.as_ref().starts_with("sleep "));195 sleep_command196 .as_ref()197 .trim_start_matches("sleep ")198 .parse::<Second>()199 .unwrap()200 }201}202Proper shell overhead computationDavid Peterbefore adoption6887835
line 203why, one step back203impl Executor for MockExecutor {Rename to run_command_and_measureDavid Peterbefore adoption7c929f7
line 204why, one step back204 fn run_command_and_measure(Add debug/mock modeDavid Peterbefore adoption6f51232
lines 205–222why, one step back205 &self,206 command: &Command<'_>,207 _command_failure_action: Option<CmdFailureAction>,208 ) -> Result<(TimingResult, ExitStatus)> {209 #[cfg(unix)]210 let status = {211 use std::os::unix::process::ExitStatusExt;212 ExitStatus::from_raw(0)213 };214215 #[cfg(windows)]216 let status = {217 use std::os::windows::process::ExitStatusExt;218 ExitStatus::from_raw(0)219 };220221 Ok((222 TimingResult {Rename to get_command_lineDavid Peterbefore adoption826449b
line 223why, one step back223 time_real: Self::extract_time(command.get_command_line()),Add debug/mock modeDavid Peterbefore adoption6f51232
lines 224–235why, one step back224 time_user: 0.0,225 time_system: 0.0,226 },227 status,228 ))229 }230231 fn calibrate(&mut self) -> Result<()> {232 Ok(())233 }234235 fn time_overhead(&self) -> Second {Proper shell overhead computationDavid Peterbefore adoption6887835
lines 236–238why, one step back236 match &self.shell {237 None => 0.0,238 Some(shell) => Self::extract_time(shell),Add debug/mock modeDavid Peterbefore adoption6f51232
lines 239–246why, one step back239 }240 }241}242243#[test]244fn test_mock_executor_extract_time() {245 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);246}