executor.rs
This file
Path
src/benchmark/executor.rs
307 lines · 9.0 KiB · Rust
Last changed by
bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
History of this fileTake it
The walk stopped after 200 commits: lines older than 02157eb point at it.
bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 1why, one step back1use std::os::windows::process::CommandExt;Add the rest of the suggestions from code reviewSteve Neasebefore adoptiond32b90e
line 2why, one step back2use std::process::ExitStatus;Add histogram imageDavid Peterbefore adoption02157eb
lines 3–4why, one step back34use crate::command::Command;ran cargo fmtSteve Neasebefore adoption0e3bad1
lines 5–7why, one step back5use crate::options::{6 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,7};Add histogram imageDavid Peterbefore adoption02157eb
lines 8–41why, one step back8use crate::output::progress_bar::get_progress_bar;9use crate::timer::{execute_and_measure, TimerResult};10use crate::util::randomized_environment_offset;11use crate::util::units::Second;1213use super::timing_result::TimingResult;1415use anyhow::{bail, Context, Result};16use statistical::mean;1718pub trait Executor {19 /// Run the given command and measure the execution time20 fn run_command_and_measure(21 &self,22 command: &Command<'_>,23 command_failure_action: Option<CmdFailureAction>,24 ) -> Result<(TimingResult, ExitStatus)>;2526 /// Perform a calibration of this executor. For example,27 /// when running commands through a shell, we need to28 /// measure the shell spawning time separately in order29 /// to subtract it from the full runtime later.30 fn calibrate(&mut self) -> Result<()>;3132 /// Return the time overhead for this executor when33 /// performing a measurement. This should return the time34 /// that is being used in addition to the actual runtime35 /// of the command.36 fn time_overhead(&self) -> Second;37}3839fn run_command_and_measure_common(40 mut command: std::process::Command,41 command_failure_action: CmdFailureAction,Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 42why, one step back42 command_input_policy: &CommandInputPolicy,Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c
line 43why, one step back43 command_output_policy: &CommandOutputPolicy,Add histogram imageDavid Peterbefore adoption02157eb
lines 44–45why, one step back44 command_name: &str,45) -> Result<TimerResult> {Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 46why, one step back46 let stdin = command_input_policy.get_stdin()?;Change order of input/oututDavid Peterbefore adoptione88fa27
line 47why, one step back47 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 48why, one step back48 command.stdin(stdin).stdout(stdout).stderr(stderr);Add histogram imageDavid Peterbefore adoption02157eb
lines 49–90why, one step back4950 command.env(51 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",52 randomized_environment_offset::value(),53 );5455 let result = execute_and_measure(command)56 .with_context(|| format!("Failed to run command '{}'", command_name))?;5758 if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {59 bail!(60 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \61 Alternatively, use the '--show-output' option to debug what went wrong.",62 result.status.code().map_or(63 "The process has been terminated by a signal".into(),64 |c| format!("Command terminated with non-zero exit code: {}", c)65 )66 );67 }6869 Ok(result)70}7172pub struct RawExecutor<'a> {73 options: &'a Options,74}7576impl<'a> RawExecutor<'a> {77 pub fn new(options: &'a Options) -> Self {78 RawExecutor { options }79 }80}8182impl<'a> Executor for RawExecutor<'a> {83 fn run_command_and_measure(84 &self,85 command: &Command<'_>,86 command_failure_action: Option<CmdFailureAction>,87 ) -> Result<(TimingResult, ExitStatus)> {88 let result = run_command_and_measure_common(89 command.get_command()?,90 command_failure_action.unwrap_or(self.options.command_failure_action),Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 91why, one step back91 &self.options.command_input_policy,Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c
line 92why, one step back92 &self.options.command_output_policy,Add histogram imageDavid Peterbefore adoption02157eb
lines 93–136why, one step back93 &command.get_command_line(),94 )?;9596 Ok((97 TimingResult {98 time_real: result.time_real,99 time_user: result.time_user,100 time_system: result.time_system,101 },102 result.status,103 ))104 }105106 fn calibrate(&mut self) -> Result<()> {107 Ok(())108 }109110 fn time_overhead(&self) -> Second {111 0.0112 }113}114115pub struct ShellExecutor<'a> {116 options: &'a Options,117 shell: &'a Shell,118 shell_spawning_time: Option<TimingResult>,119}120121impl<'a> ShellExecutor<'a> {122 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {123 ShellExecutor {124 shell,125 options,126 shell_spawning_time: None,127 }128 }129}130131impl<'a> Executor for ShellExecutor<'a> {132 fn run_command_and_measure(133 &self,134 command: &Command<'_>,135 command_failure_action: Option<CmdFailureAction>,136 ) -> Result<(TimingResult, ExitStatus)> { bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 137why, one step back137 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");Add histogram imageDavid Peterbefore adoption02157eb
lines 138–139why, one step back138 let mut command_builder = self.shell.command();139 command_builderFixes #568FilipAnderssonbefore adoptionf00acf9
line 140why, one step back140 .arg( bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 141why, one step back141 if on_windows_cmd {Fixes #568FilipAnderssonbefore adoptionf00acf9
lines 142–145why, one step back142 "/C"143 } else {144 "-c"145 }, bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
lines 146–153why, one step back146 );147148 // Windows needs special treatment for its behavior on parsing cmd arguments149 if on_windows_cmd {150 command_builder.raw_arg(command.get_command_line());151 } else {152 command_builder.arg(command.get_command_line());153 }Add histogram imageDavid Peterbefore adoption02157eb
lines 154–157why, one step back154155 let mut result = run_command_and_measure_common(156 command_builder,157 command_failure_action.unwrap_or(self.options.command_failure_action),Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 158why, one step back158 &self.options.command_input_policy,Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c
line 159why, one step back159 &self.options.command_output_policy,Add histogram imageDavid Peterbefore adoption02157eb
lines 160–307why, one step back160 &command.get_command_line(),161 )?;162163 // Subtract shell spawning time164 if let Some(spawning_time) = self.shell_spawning_time {165 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);166 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);167 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);168 }169170 Ok((171 TimingResult {172 time_real: result.time_real,173 time_user: result.time_user,174 time_system: result.time_system,175 },176 result.status,177 ))178 }179180 /// Measure the average shell spawning time181 fn calibrate(&mut self) -> Result<()> {182 const COUNT: u64 = 50;183 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {184 Some(get_progress_bar(185 COUNT,186 "Measuring shell spawning time",187 self.options.output_style,188 ))189 } else {190 None191 };192193 let mut times_real: Vec<Second> = vec![];194 let mut times_user: Vec<Second> = vec![];195 let mut times_system: Vec<Second> = vec![];196197 for _ in 0..COUNT {198 // Just run the shell without any command199 let res = self.run_command_and_measure(&Command::new(None, ""), None);200201 match res {202 Err(_) => {203 let shell_cmd = if cfg!(windows) {204 format!("{} /C \"\"", self.shell)205 } else {206 format!("{} -c \"\"", self.shell)207 };208209 bail!(210 "Could not measure shell execution time. Make sure you can run '{}'.",211 shell_cmd212 );213 }214 Ok((r, _)) => {215 times_real.push(r.time_real);216 times_user.push(r.time_user);217 times_system.push(r.time_system);218 }219 }220221 if let Some(bar) = progress_bar.as_ref() {222 bar.inc(1)223 }224 }225226 if let Some(bar) = progress_bar.as_ref() {227 bar.finish_and_clear()228 }229230 self.shell_spawning_time = Some(TimingResult {231 time_real: mean(×_real),232 time_user: mean(×_user),233 time_system: mean(×_system),234 });235236 Ok(())237 }238239 fn time_overhead(&self) -> Second {240 self.shell_spawning_time.unwrap().time_real241 }242}243244#[derive(Clone)]245pub struct MockExecutor {246 shell: Option<String>,247}248249impl MockExecutor {250 pub fn new(shell: Option<String>) -> Self {251 MockExecutor { shell }252 }253254 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {255 assert!(sleep_command.as_ref().starts_with("sleep "));256 sleep_command257 .as_ref()258 .trim_start_matches("sleep ")259 .parse::<Second>()260 .unwrap()261 }262}263264impl Executor for MockExecutor {265 fn run_command_and_measure(266 &self,267 command: &Command<'_>,268 _command_failure_action: Option<CmdFailureAction>,269 ) -> Result<(TimingResult, ExitStatus)> {270 #[cfg(unix)]271 let status = {272 use std::os::unix::process::ExitStatusExt;273 ExitStatus::from_raw(0)274 };275276 #[cfg(windows)]277 let status = {278 use std::os::windows::process::ExitStatusExt;279 ExitStatus::from_raw(0)280 };281282 Ok((283 TimingResult {284 time_real: Self::extract_time(command.get_command_line()),285 time_user: 0.0,286 time_system: 0.0,287 },288 status,289 ))290 }291292 fn calibrate(&mut self) -> Result<()> {293 Ok(())294 }295296 fn time_overhead(&self) -> Second {297 match &self.shell {298 None => 0.0,299 Some(shell) => Self::extract_time(shell),300 }301 }302}303304#[test]305fn test_mock_executor_extract_time() {306 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);307}