executor.rs
This file
Path
src/benchmark/executor.rs
302 lines · 8.9 KiB · Rust
Last changed by
cfg: adding more pre-processing for windows-only parserPedro Witzelbefore adoptionae9b0bb
History of this fileTake it
The walk stopped after 200 commits: lines older than 251a697 point at it.
fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
line 1why, one step back1#[cfg(windows)] bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 2why, one step back2use std::os::windows::process::CommandExt;Add the rest of the suggestions from code reviewSteve Neasebefore adoptiond32b90e
line 3why, one step back3use std::process::ExitStatus;Bump libc from 0.2.121 to 0.2.125dependabot[bot]before adoption251a697
lines 4–5why, one step back45use crate::command::Command;ran cargo fmtSteve Neasebefore adoption0e3bad1
lines 6–8why, one step back6use crate::options::{7 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,8};Bump libc from 0.2.121 to 0.2.125dependabot[bot]before adoption251a697
lines 9–42why, one step back9use crate::output::progress_bar::get_progress_bar;10use crate::timer::{execute_and_measure, TimerResult};11use crate::util::randomized_environment_offset;12use crate::util::units::Second;1314use super::timing_result::TimingResult;1516use anyhow::{bail, Context, Result};17use statistical::mean;1819pub trait Executor {20 /// Run the given command and measure the execution time21 fn run_command_and_measure(22 &self,23 command: &Command<'_>,24 command_failure_action: Option<CmdFailureAction>,25 ) -> Result<(TimingResult, ExitStatus)>;2627 /// Perform a calibration of this executor. For example,28 /// when running commands through a shell, we need to29 /// measure the shell spawning time separately in order30 /// to subtract it from the full runtime later.31 fn calibrate(&mut self) -> Result<()>;3233 /// Return the time overhead for this executor when34 /// performing a measurement. This should return the time35 /// that is being used in addition to the actual runtime36 /// of the command.37 fn time_overhead(&self) -> Second;38}3940fn run_command_and_measure_common(41 mut command: std::process::Command,42 command_failure_action: CmdFailureAction,Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 43why, one step back43 command_input_policy: &CommandInputPolicy,Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c
line 44why, one step back44 command_output_policy: &CommandOutputPolicy,Bump libc from 0.2.121 to 0.2.125dependabot[bot]before adoption251a697
lines 45–46why, one step back45 command_name: &str,46) -> Result<TimerResult> {Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 47why, one step back47 let stdin = command_input_policy.get_stdin()?;Change order of input/oututDavid Peterbefore adoptione88fa27
line 48why, one step back48 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 49why, one step back49 command.stdin(stdin).stdout(stdout).stderr(stderr);Bump libc from 0.2.121 to 0.2.125dependabot[bot]before adoption251a697
lines 50–91why, one step back5051 command.env(52 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",53 randomized_environment_offset::value(),54 );5556 let result = execute_and_measure(command)57 .with_context(|| format!("Failed to run command '{}'", command_name))?;5859 if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {60 bail!(61 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \62 Alternatively, use the '--show-output' option to debug what went wrong.",63 result.status.code().map_or(64 "The process has been terminated by a signal".into(),65 |c| format!("Command terminated with non-zero exit code: {}", c)66 )67 );68 }6970 Ok(result)71}7273pub struct RawExecutor<'a> {74 options: &'a Options,75}7677impl<'a> RawExecutor<'a> {78 pub fn new(options: &'a Options) -> Self {79 RawExecutor { options }80 }81}8283impl<'a> Executor for RawExecutor<'a> {84 fn run_command_and_measure(85 &self,86 command: &Command<'_>,87 command_failure_action: Option<CmdFailureAction>,88 ) -> Result<(TimingResult, ExitStatus)> {89 let result = run_command_and_measure_common(90 command.get_command()?,91 command_failure_action.unwrap_or(self.options.command_failure_action),Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 92why, one step back92 &self.options.command_input_policy,Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c
line 93why, one step back93 &self.options.command_output_policy,Bump libc from 0.2.121 to 0.2.125dependabot[bot]before adoption251a697
lines 94–137why, one step back94 &command.get_command_line(),95 )?;9697 Ok((98 TimingResult {99 time_real: result.time_real,100 time_user: result.time_user,101 time_system: result.time_system,102 },103 result.status,104 ))105 }106107 fn calibrate(&mut self) -> Result<()> {108 Ok(())109 }110111 fn time_overhead(&self) -> Second {112 0.0113 }114}115116pub struct ShellExecutor<'a> {117 options: &'a Options,118 shell: &'a Shell,119 shell_spawning_time: Option<TimingResult>,120}121122impl<'a> ShellExecutor<'a> {123 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {124 ShellExecutor {125 shell,126 options,127 shell_spawning_time: None,128 }129 }130}131132impl<'a> Executor for ShellExecutor<'a> {133 fn run_command_and_measure(134 &self,135 command: &Command<'_>,136 command_failure_action: Option<CmdFailureAction>,137 ) -> Result<(TimingResult, ExitStatus)> { bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 138why, one step back138 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");Bump libc from 0.2.121 to 0.2.125dependabot[bot]before adoption251a697
line 139why, one step back139 let mut command_builder = self.shell.command();fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
line 140why, one step back140 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" }); bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 141why, one step back141fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 142–143why, one step back142 // Windows needs special treatment for its behavior on parsing cmd arguments143 if on_windows_cmd {cfg: adding more pre-processing for windows-only parserPedro Witzelbefore adoptionae9b0bb
line 144why, one step back144 #[cfg(windows)]fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 145–148why, one step back145 command_builder.raw_arg(command.get_command_line());146 } else {147 command_builder.arg(command.get_command_line());148 }Bump libc from 0.2.121 to 0.2.125dependabot[bot]before adoption251a697
lines 149–152why, one step back149150 let mut result = run_command_and_measure_common(151 command_builder,152 command_failure_action.unwrap_or(self.options.command_failure_action),Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 153why, one step back153 &self.options.command_input_policy,Implement --output={null,pipe,<FILE>}Tavian Barnesbefore adoption277807c
line 154why, one step back154 &self.options.command_output_policy,Bump libc from 0.2.121 to 0.2.125dependabot[bot]before adoption251a697
lines 155–302why, one step back155 &command.get_command_line(),156 )?;157158 // Subtract shell spawning time159 if let Some(spawning_time) = self.shell_spawning_time {160 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);161 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);162 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);163 }164165 Ok((166 TimingResult {167 time_real: result.time_real,168 time_user: result.time_user,169 time_system: result.time_system,170 },171 result.status,172 ))173 }174175 /// Measure the average shell spawning time176 fn calibrate(&mut self) -> Result<()> {177 const COUNT: u64 = 50;178 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {179 Some(get_progress_bar(180 COUNT,181 "Measuring shell spawning time",182 self.options.output_style,183 ))184 } else {185 None186 };187188 let mut times_real: Vec<Second> = vec![];189 let mut times_user: Vec<Second> = vec![];190 let mut times_system: Vec<Second> = vec![];191192 for _ in 0..COUNT {193 // Just run the shell without any command194 let res = self.run_command_and_measure(&Command::new(None, ""), None);195196 match res {197 Err(_) => {198 let shell_cmd = if cfg!(windows) {199 format!("{} /C \"\"", self.shell)200 } else {201 format!("{} -c \"\"", self.shell)202 };203204 bail!(205 "Could not measure shell execution time. Make sure you can run '{}'.",206 shell_cmd207 );208 }209 Ok((r, _)) => {210 times_real.push(r.time_real);211 times_user.push(r.time_user);212 times_system.push(r.time_system);213 }214 }215216 if let Some(bar) = progress_bar.as_ref() {217 bar.inc(1)218 }219 }220221 if let Some(bar) = progress_bar.as_ref() {222 bar.finish_and_clear()223 }224225 self.shell_spawning_time = Some(TimingResult {226 time_real: mean(×_real),227 time_user: mean(×_user),228 time_system: mean(×_system),229 });230231 Ok(())232 }233234 fn time_overhead(&self) -> Second {235 self.shell_spawning_time.unwrap().time_real236 }237}238239#[derive(Clone)]240pub struct MockExecutor {241 shell: Option<String>,242}243244impl MockExecutor {245 pub fn new(shell: Option<String>) -> Self {246 MockExecutor { shell }247 }248249 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {250 assert!(sleep_command.as_ref().starts_with("sleep "));251 sleep_command252 .as_ref()253 .trim_start_matches("sleep ")254 .parse::<Second>()255 .unwrap()256 }257}258259impl Executor for MockExecutor {260 fn run_command_and_measure(261 &self,262 command: &Command<'_>,263 _command_failure_action: Option<CmdFailureAction>,264 ) -> Result<(TimingResult, ExitStatus)> {265 #[cfg(unix)]266 let status = {267 use std::os::unix::process::ExitStatusExt;268 ExitStatus::from_raw(0)269 };270271 #[cfg(windows)]272 let status = {273 use std::os::windows::process::ExitStatusExt;274 ExitStatus::from_raw(0)275 };276277 Ok((278 TimingResult {279 time_real: Self::extract_time(command.get_command_line()),280 time_user: 0.0,281 time_system: 0.0,282 },283 status,284 ))285 }286287 fn calibrate(&mut self) -> Result<()> {288 Ok(())289 }290291 fn time_overhead(&self) -> Second {292 match &self.shell {293 None => 0.0,294 Some(shell) => Self::extract_time(shell),295 }296 }297}298299#[test]300fn test_mock_executor_extract_time() {301 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);302}