executor.rs
This file
Path
src/benchmark/executor.rs
249 lines · 7.6 KiB · Rust
Last changed by
Further simplify execute_and_measureDavid Peterbefore adoptione1da8ba
History of this fileTake it
Add debug/mock modeDavid Peterbefore adoption6f51232
lines 1–5why, one step back1use std::process::{ExitStatus, Stdio};23use crate::command::Command;4use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};5use crate::output::progress_bar::get_progress_bar;Move to timer moduleDavid Peterbefore adoption0ffc6d7
line 6why, one step back6use crate::timer::{execute_and_measure, wall_clock_timer::WallClockTimer};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–70why, one step back62 &self,63 command: &Command<'_>,64 command_failure_action: Option<CmdFailureAction>,65 ) -> Result<(TimingResult, ExitStatus)> {66 let (stdout, stderr) = match self.options.command_output_policy {67 CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),68 CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),69 };70Move custom functionality to executorDavid Peterbefore adoption1f3943e
lines 71–82why, one step back71 let mut command_builder = self.shell.command();72 command_builder73 .arg(if cfg!(windows) { "/C" } else { "-c" })74 .arg(command.get_command_line())75 .env(76 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",77 randomized_environment_offset::value(),78 )79 .stdin(Stdio::null())80 .stdout(stdout)81 .stderr(stderr);82Add debug/mock modeDavid Peterbefore adoption6f51232
line 83why, one step back83 let wallclock_timer = WallClockTimer::start();Further simplify execute_and_measureDavid Peterbefore adoptione1da8ba
lines 84–85why, one step back84 let result = execute_and_measure(command_builder)85 .with_context(|| format!("Failed to run command '{}'", command.get_command_line()))?;Add debug/mock modeDavid Peterbefore adoption6f51232
lines 86–140why, one step back86 let mut time_real = wallclock_timer.stop();8788 let mut time_user = result.user_time;89 let mut time_system = result.system_time;9091 if command_failure_action.unwrap_or(self.options.command_failure_action)92 == CmdFailureAction::RaiseError93 && !result.status.success()94 {95 bail!(96 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \97 Alternatively, use the '--show-output' option to debug what went wrong.",98 result.status.code().map_or(99 "The process has been terminated by a signal".into(),100 |c| format!("Command terminated with non-zero exit code: {}", c)101 )102 );103 }104105 // Subtract shell spawning time106 if let Some(spawning_time) = self.shell_spawning_time {107 time_real = self.subtract_shell_spawning_time(time_real, spawning_time.time_real);108 time_user = self.subtract_shell_spawning_time(time_user, spawning_time.time_user);109 time_system = self.subtract_shell_spawning_time(time_system, spawning_time.time_system);110 }111112 Ok((113 TimingResult {114 time_real,115 time_user,116 time_system,117 },118 result.status,119 ))120 }121122 /// Measure the average shell spawning time123 fn calibrate(&mut self) -> Result<()> {124 const COUNT: u64 = 50;125 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {126 Some(get_progress_bar(127 COUNT,128 "Measuring shell spawning time",129 self.options.output_style,130 ))131 } else {132 None133 };134135 let mut times_real: Vec<Second> = vec![];136 let mut times_user: Vec<Second> = vec![];137 let mut times_system: Vec<Second> = vec![];138139 for _ in 0..COUNT {140 // Just run the shell without any commandRename to run_command_and_measureDavid Peterbefore adoption7c929f7
line 141why, one step back141 let res = self.run_command_and_measure(&Command::new(None, ""), None);Add debug/mock modeDavid Peterbefore adoption6f51232
lines 142–186why, one step back142143 match res {144 Err(_) => {145 let shell_cmd = if cfg!(windows) {146 format!("{} /C \"\"", self.shell)147 } else {148 format!("{} -c \"\"", self.shell)149 };150151 bail!(152 "Could not measure shell execution time. Make sure you can run '{}'.",153 shell_cmd154 );155 }156 Ok((r, _)) => {157 times_real.push(r.time_real);158 times_user.push(r.time_user);159 times_system.push(r.time_system);160 }161 }162163 if let Some(bar) = progress_bar.as_ref() {164 bar.inc(1)165 }166 }167168 if let Some(bar) = progress_bar.as_ref() {169 bar.finish_and_clear()170 }171172 self.shell_spawning_time = Some(TimingResult {173 time_real: mean(×_real),174 time_user: mean(×_user),175 time_system: mean(×_system),176 });177178 Ok(())179 }180181 fn time_overhead(&self) -> Second {182 self.shell_spawning_time.unwrap().time_real183 }184}185186#[derive(Clone)]Proper shell overhead computationDavid Peterbefore adoption6887835
lines 187–188why, one step back187pub struct MockExecutor {188 shell: Option<String>,Add debug/mock modeDavid Peterbefore adoption6f51232
lines 189–190why, one step back189}190Proper shell overhead computationDavid Peterbefore adoption6887835
lines 191–192why, one step back191impl MockExecutor {192 pub fn new(shell: Option<String>) -> Self {Add debug/mock modeDavid Peterbefore adoption6f51232
lines 193–205why, one step back193 MockExecutor { shell }194 }195196 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {197 assert!(sleep_command.as_ref().starts_with("sleep "));198 sleep_command199 .as_ref()200 .trim_start_matches("sleep ")201 .parse::<Second>()202 .unwrap()203 }204}205Proper shell overhead computationDavid Peterbefore adoption6887835
line 206why, one step back206impl Executor for MockExecutor {Rename to run_command_and_measureDavid Peterbefore adoption7c929f7
line 207why, one step back207 fn run_command_and_measure(Add debug/mock modeDavid Peterbefore adoption6f51232
lines 208–225why, one step back208 &self,209 command: &Command<'_>,210 _command_failure_action: Option<CmdFailureAction>,211 ) -> Result<(TimingResult, ExitStatus)> {212 #[cfg(unix)]213 let status = {214 use std::os::unix::process::ExitStatusExt;215 ExitStatus::from_raw(0)216 };217218 #[cfg(windows)]219 let status = {220 use std::os::windows::process::ExitStatusExt;221 ExitStatus::from_raw(0)222 };223224 Ok((225 TimingResult {Rename to get_command_lineDavid Peterbefore adoption826449b
line 226why, one step back226 time_real: Self::extract_time(command.get_command_line()),Add debug/mock modeDavid Peterbefore adoption6f51232
lines 227–238why, one step back227 time_user: 0.0,228 time_system: 0.0,229 },230 status,231 ))232 }233234 fn calibrate(&mut self) -> Result<()> {235 Ok(())236 }237238 fn time_overhead(&self) -> Second {Proper shell overhead computationDavid Peterbefore adoption6887835
lines 239–241why, one step back239 match &self.shell {240 None => 0.0,241 Some(shell) => Self::extract_time(shell),Add debug/mock modeDavid Peterbefore adoption6f51232
lines 242–249why, one step back242 }243 }244}245246#[test]247fn test_mock_executor_extract_time() {248 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);249}