executor.rs
This file
Path
src/benchmark/executor.rs
299 lines · 8.7 KiB · Rust
Last changed by
Change order of input/oututDavid Peterbefore adoptione88fa27
History of this fileTake it
1use std::process::ExitStatus;23use crate::command::Command;4use crate::options::{5 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,6};7use crate::output::progress_bar::get_progress_bar;8use crate::timer::{execute_and_measure, TimerResult};9use crate::util::randomized_environment_offset;10use crate::util::units::Second;1112use super::timing_result::TimingResult;1314use anyhow::{bail, Context, Result};15use statistical::mean;1617pub trait Executor {18 /// Run the given command and measure the execution time19 fn run_command_and_measure(20 &self,21 command: &Command<'_>,22 command_failure_action: Option<CmdFailureAction>,23 ) -> Result<(TimingResult, ExitStatus)>;2425 /// Perform a calibration of this executor. For example,26 /// when running commands through a shell, we need to27 /// measure the shell spawning time separately in order28 /// to subtract it from the full runtime later.29 fn calibrate(&mut self) -> Result<()>;3031 /// Return the time overhead for this executor when32 /// performing a measurement. This should return the time33 /// that is being used in addition to the actual runtime34 /// of the command.35 fn time_overhead(&self) -> Second;36}3738fn run_command_and_measure_common(39 mut command: std::process::Command,40 command_failure_action: CmdFailureAction,41 command_input_policy: &CommandInputPolicy,42 command_output_policy: &CommandOutputPolicy,43 command_name: &str,44) -> Result<TimerResult> {45 let stdin = command_input_policy.get_stdin()?;46 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;47 command.stdin(stdin).stdout(stdout).stderr(stderr);4849 command.env(50 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",51 randomized_environment_offset::value(),52 );5354 let result = execute_and_measure(command)55 .with_context(|| format!("Failed to run command '{}'", command_name))?;5657 if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {58 bail!(59 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \60 Alternatively, use the '--show-output' option to debug what went wrong.",61 result.status.code().map_or(62 "The process has been terminated by a signal".into(),63 |c| format!("Command terminated with non-zero exit code: {}", c)64 )65 );66 }6768 Ok(result)69}7071pub struct RawExecutor<'a> {72 options: &'a Options,73}7475impl<'a> RawExecutor<'a> {76 pub fn new(options: &'a Options) -> Self {77 RawExecutor { options }78 }79}8081impl<'a> Executor for RawExecutor<'a> {82 fn run_command_and_measure(83 &self,84 command: &Command<'_>,85 command_failure_action: Option<CmdFailureAction>,86 ) -> Result<(TimingResult, ExitStatus)> {87 let result = run_command_and_measure_common(88 command.get_command()?,89 command_failure_action.unwrap_or(self.options.command_failure_action),90 &self.options.command_input_policy,91 &self.options.command_output_policy,92 &command.get_command_line(),93 )?;9495 Ok((96 TimingResult {97 time_real: result.time_real,98 time_user: result.time_user,99 time_system: result.time_system,100 },101 result.status,102 ))103 }104105 fn calibrate(&mut self) -> Result<()> {106 Ok(())107 }108109 fn time_overhead(&self) -> Second {110 0.0111 }112}113114pub struct ShellExecutor<'a> {115 options: &'a Options,116 shell: &'a Shell,117 shell_spawning_time: Option<TimingResult>,118}119120impl<'a> ShellExecutor<'a> {121 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {122 ShellExecutor {123 shell,124 options,125 shell_spawning_time: None,126 }127 }128}129130impl<'a> Executor for ShellExecutor<'a> {131 fn run_command_and_measure(132 &self,133 command: &Command<'_>,134 command_failure_action: Option<CmdFailureAction>,135 ) -> Result<(TimingResult, ExitStatus)> {136 let mut command_builder = self.shell.command();137 command_builder138 .arg(139 if cfg!(windows) && *self.shell == Shell::Default("cmd.exe") {140 "/C"141 } else {142 "-c"143 },144 )145 .arg(command.get_command_line());146147 let mut result = run_command_and_measure_common(148 command_builder,149 command_failure_action.unwrap_or(self.options.command_failure_action),150 &self.options.command_input_policy,151 &self.options.command_output_policy,152 &command.get_command_line(),153 )?;154155 // Subtract shell spawning time156 if let Some(spawning_time) = self.shell_spawning_time {157 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);158 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);159 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);160 }161162 Ok((163 TimingResult {164 time_real: result.time_real,165 time_user: result.time_user,166 time_system: result.time_system,167 },168 result.status,169 ))170 }171172 /// Measure the average shell spawning time173 fn calibrate(&mut self) -> Result<()> {174 const COUNT: u64 = 50;175 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {176 Some(get_progress_bar(177 COUNT,178 "Measuring shell spawning time",179 self.options.output_style,180 ))181 } else {182 None183 };184185 let mut times_real: Vec<Second> = vec![];186 let mut times_user: Vec<Second> = vec![];187 let mut times_system: Vec<Second> = vec![];188189 for _ in 0..COUNT {190 // Just run the shell without any command191 let res = self.run_command_and_measure(&Command::new(None, ""), None);192193 match res {194 Err(_) => {195 let shell_cmd = if cfg!(windows) {196 format!("{} /C \"\"", self.shell)197 } else {198 format!("{} -c \"\"", self.shell)199 };200201 bail!(202 "Could not measure shell execution time. Make sure you can run '{}'.",203 shell_cmd204 );205 }206 Ok((r, _)) => {207 times_real.push(r.time_real);208 times_user.push(r.time_user);209 times_system.push(r.time_system);210 }211 }212213 if let Some(bar) = progress_bar.as_ref() {214 bar.inc(1)215 }216 }217218 if let Some(bar) = progress_bar.as_ref() {219 bar.finish_and_clear()220 }221222 self.shell_spawning_time = Some(TimingResult {223 time_real: mean(×_real),224 time_user: mean(×_user),225 time_system: mean(×_system),226 });227228 Ok(())229 }230231 fn time_overhead(&self) -> Second {232 self.shell_spawning_time.unwrap().time_real233 }234}235236#[derive(Clone)]237pub struct MockExecutor {238 shell: Option<String>,239}240241impl MockExecutor {242 pub fn new(shell: Option<String>) -> Self {243 MockExecutor { shell }244 }245246 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {247 assert!(sleep_command.as_ref().starts_with("sleep "));248 sleep_command249 .as_ref()250 .trim_start_matches("sleep ")251 .parse::<Second>()252 .unwrap()253 }254}255256impl Executor for MockExecutor {257 fn run_command_and_measure(258 &self,259 command: &Command<'_>,260 _command_failure_action: Option<CmdFailureAction>,261 ) -> Result<(TimingResult, ExitStatus)> {262 #[cfg(unix)]263 let status = {264 use std::os::unix::process::ExitStatusExt;265 ExitStatus::from_raw(0)266 };267268 #[cfg(windows)]269 let status = {270 use std::os::windows::process::ExitStatusExt;271 ExitStatus::from_raw(0)272 };273274 Ok((275 TimingResult {276 time_real: Self::extract_time(command.get_command_line()),277 time_user: 0.0,278 time_system: 0.0,279 },280 status,281 ))282 }283284 fn calibrate(&mut self) -> Result<()> {285 Ok(())286 }287288 fn time_overhead(&self) -> Second {289 match &self.shell {290 None => 0.0,291 Some(shell) => Self::extract_time(shell),292 }293 }294}295296#[test]297fn test_mock_executor_extract_time() {298 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);299}