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 fileTake it
1use std::process::{ExitStatus, Stdio};23use crate::command::Command;4use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};5use crate::output::progress_bar::get_progress_bar;6use crate::timer::{execute_and_measure, TimerResult};7use crate::util::randomized_environment_offset;8use crate::util::units::Second;910use super::timing_result::TimingResult;1112use anyhow::{bail, Context, Result};13use statistical::mean;1415pub trait Executor {16 /// Run the given command and measure the execution time17 fn run_command_and_measure(18 &self,19 command: &Command<'_>,20 command_failure_action: Option<CmdFailureAction>,21 ) -> Result<(TimingResult, ExitStatus)>;2223 /// 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.27 fn calibrate(&mut self) -> Result<()>;2829 /// 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.33 fn time_overhead(&self) -> Second;34}3536fn 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}6667pub 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}108109pub 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> {126 fn run_command_and_measure(127 &self,128 command: &Command<'_>,129 command_failure_action: Option<CmdFailureAction>,130 ) -> Result<(TimingResult, ExitStatus)> {131 let mut command_builder = self.shell.command();132 command_builder133 .arg(if cfg!(windows) { "/C" } else { "-c" })134 .arg(command.get_command_line());135136 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 )?;142143 // Subtract shell spawning time144 if let Some(spawning_time) = self.shell_spawning_time {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);148 }149150 Ok((151 TimingResult {152 time_real: result.time_real,153 time_user: result.time_user,154 time_system: result.time_system,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 command179 let res = self.run_command_and_measure(&Command::new(None, ""), None);180181 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)]225pub struct MockExecutor {226 shell: Option<String>,227}228229impl MockExecutor {230 pub fn new(shell: Option<String>) -> Self {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}243244impl Executor for MockExecutor {245 fn run_command_and_measure(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 {264 time_real: Self::extract_time(command.get_command_line()),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 {277 match &self.shell {278 None => 0.0,279 Some(shell) => Self::extract_time(shell),280 }281 }282}283284#[test]285fn test_mock_executor_extract_time() {286 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);287}