executor.rs
This file
Path
src/benchmark/executor.rs
341 lines · 10.2 KiB · Rust
Last changed by
Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
History of this fileTake it
The walk stopped after 200 commits: lines older than 2e8ce30 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;Shrink unsafe blockcactterbefore adoption2e8ce30
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};Shrink unsafe blockcactterbefore adoption2e8ce30
lines 9–18why, 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;18Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 19–34why, one step back19pub enum BenchmarkIteration {20 NonBenchmarkRun,21 Warmup(u64),22 Benchmark(u64),23}2425impl BenchmarkIteration {26 pub fn to_env_var_value(&self) -> Option<String> {27 match self {28 BenchmarkIteration::NonBenchmarkRun => None,29 BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)),30 BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)),31 }32 }33}34Shrink unsafe blockcactterbefore adoption2e8ce30
lines 35–39why, one step back35pub trait Executor {36 /// Run the given command and measure the execution time37 fn run_command_and_measure(38 &self,39 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 40why, one step back40 iteration: BenchmarkIteration,Shrink unsafe blockcactterbefore adoption2e8ce30
lines 41–58why, one step back41 command_failure_action: Option<CmdFailureAction>,42 ) -> Result<(TimingResult, ExitStatus)>;4344 /// Perform a calibration of this executor. For example,45 /// when running commands through a shell, we need to46 /// measure the shell spawning time separately in order47 /// to subtract it from the full runtime later.48 fn calibrate(&mut self) -> Result<()>;4950 /// Return the time overhead for this executor when51 /// performing a measurement. This should return the time52 /// that is being used in addition to the actual runtime53 /// of the command.54 fn time_overhead(&self) -> Second;55}5657fn run_command_and_measure_common(58 mut command: std::process::Command,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 59why, one step back59 iteration: BenchmarkIteration,Shrink unsafe blockcactterbefore adoption2e8ce30
line 60why, one step back60 command_failure_action: CmdFailureAction,Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 61why, one step back61 command_input_policy: &CommandInputPolicy,Shrink unsafe blockcactterbefore adoption2e8ce30
lines 62–64why, one step back62 command_output_policy: &CommandOutputPolicy,63 command_name: &str,64) -> Result<TimerResult> {Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 65why, one step back65 let stdin = command_input_policy.get_stdin()?;Change order of input/oututDavid Peterbefore adoptione88fa27
line 66why, one step back66 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 67why, one step back67 command.stdin(stdin).stdout(stdout).stderr(stderr);Shrink unsafe blockcactterbefore adoption2e8ce30
lines 68–73why, one step back6869 command.env(70 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",71 randomized_environment_offset::value(),72 );73Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 74–77why, one step back74 if let Some(value) = iteration.to_env_var_value() {75 command.env("HYPERFINE_ITERATION", value);76 }77Shrink unsafe blockcactterbefore adoption2e8ce30
line 78why, one step back78 let result = execute_and_measure(command)style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 79why, one step back79 .with_context(|| format!("Failed to run command '{command_name}'"))?;Shrink unsafe blockcactterbefore adoption2e8ce30
lines 80–81why, one step back8081 if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 82–88why, one step back82 let when = match iteration {83 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),84 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),85 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),86 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),87 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),88 };Shrink unsafe blockcactterbefore adoption2e8ce30
line 89why, one step back89 bail!(Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 90why, one step back90 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \Shrink unsafe blockcactterbefore adoption2e8ce30
line 91why, one step back91 Alternatively, use the '--show-output' option to debug what went wrong.",Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 92why, one step back92 cause=result.status.code().map_or(Shrink unsafe blockcactterbefore adoption2e8ce30
line 93why, one step back93 "The process has been terminated by a signal".into(),Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 94–96why, one step back94 |c| format!("Command terminated with non-zero exit code {c}")9596 ),Shrink unsafe blockcactterbefore adoption2e8ce30
lines 97–116why, one step back97 );98 }99100 Ok(result)101}102103pub struct RawExecutor<'a> {104 options: &'a Options,105}106107impl<'a> RawExecutor<'a> {108 pub fn new(options: &'a Options) -> Self {109 RawExecutor { options }110 }111}112113impl<'a> Executor for RawExecutor<'a> {114 fn run_command_and_measure(115 &self,116 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 117why, one step back117 iteration: BenchmarkIteration,Shrink unsafe blockcactterbefore adoption2e8ce30
lines 118–121why, one step back118 command_failure_action: Option<CmdFailureAction>,119 ) -> Result<(TimingResult, ExitStatus)> {120 let result = run_command_and_measure_common(121 command.get_command()?,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 122why, one step back122 iteration,Shrink unsafe blockcactterbefore adoption2e8ce30
line 123why, one step back123 command_failure_action.unwrap_or(self.options.command_failure_action),Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 124why, one step back124 &self.options.command_input_policy,Shrink unsafe blockcactterbefore adoption2e8ce30
lines 125–167why, one step back125 &self.options.command_output_policy,126 &command.get_command_line(),127 )?;128129 Ok((130 TimingResult {131 time_real: result.time_real,132 time_user: result.time_user,133 time_system: result.time_system,134 },135 result.status,136 ))137 }138139 fn calibrate(&mut self) -> Result<()> {140 Ok(())141 }142143 fn time_overhead(&self) -> Second {144 0.0145 }146}147148pub struct ShellExecutor<'a> {149 options: &'a Options,150 shell: &'a Shell,151 shell_spawning_time: Option<TimingResult>,152}153154impl<'a> ShellExecutor<'a> {155 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {156 ShellExecutor {157 shell,158 options,159 shell_spawning_time: None,160 }161 }162}163164impl<'a> Executor for ShellExecutor<'a> {165 fn run_command_and_measure(166 &self,167 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 168why, one step back168 iteration: BenchmarkIteration,Shrink unsafe blockcactterbefore adoption2e8ce30
lines 169–170why, one step back169 command_failure_action: Option<CmdFailureAction>,170 ) -> Result<(TimingResult, ExitStatus)> { bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 171why, one step back171 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");Shrink unsafe blockcactterbefore adoption2e8ce30
line 172why, one step back172 let mut command_builder = self.shell.command();fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
line 173why, one step back173 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" }); bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 174why, one step back174fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 175–176why, one step back175 // Windows needs special treatment for its behavior on parsing cmd arguments176 if on_windows_cmd {cfg: adding more pre-processing for windows-only parserPedro Witzelbefore adoptionae9b0bb
line 177why, one step back177 #[cfg(windows)]fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 178–181why, one step back178 command_builder.raw_arg(command.get_command_line());179 } else {180 command_builder.arg(command.get_command_line());181 }Shrink unsafe blockcactterbefore adoption2e8ce30
lines 182–184why, one step back182183 let mut result = run_command_and_measure_common(184 command_builder,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 185why, one step back185 iteration,Shrink unsafe blockcactterbefore adoption2e8ce30
line 186why, one step back186 command_failure_action.unwrap_or(self.options.command_failure_action),Added --stdin-data argumentSteve Neasebefore adoptione38acdb
line 187why, one step back187 &self.options.command_input_policy,Shrink unsafe blockcactterbefore adoption2e8ce30
lines 188–227why, one step back188 &self.options.command_output_policy,189 &command.get_command_line(),190 )?;191192 // Subtract shell spawning time193 if let Some(spawning_time) = self.shell_spawning_time {194 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);195 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);196 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);197 }198199 Ok((200 TimingResult {201 time_real: result.time_real,202 time_user: result.time_user,203 time_system: result.time_system,204 },205 result.status,206 ))207 }208209 /// Measure the average shell spawning time210 fn calibrate(&mut self) -> Result<()> {211 const COUNT: u64 = 50;212 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {213 Some(get_progress_bar(214 COUNT,215 "Measuring shell spawning time",216 self.options.output_style,217 ))218 } else {219 None220 };221222 let mut times_real: Vec<Second> = vec![];223 let mut times_user: Vec<Second> = vec![];224 let mut times_system: Vec<Second> = vec![];225226 for _ in 0..COUNT {227 // Just run the shell without any commandAdd iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 228–232why, one step back228 let res = self.run_command_and_measure(229 &Command::new(None, ""),230 BenchmarkIteration::NonBenchmarkRun,231 None,232 );Shrink unsafe blockcactterbefore adoption2e8ce30
lines 233–300why, one step back233234 match res {235 Err(_) => {236 let shell_cmd = if cfg!(windows) {237 format!("{} /C \"\"", self.shell)238 } else {239 format!("{} -c \"\"", self.shell)240 };241242 bail!(243 "Could not measure shell execution time. Make sure you can run '{}'.",244 shell_cmd245 );246 }247 Ok((r, _)) => {248 times_real.push(r.time_real);249 times_user.push(r.time_user);250 times_system.push(r.time_system);251 }252 }253254 if let Some(bar) = progress_bar.as_ref() {255 bar.inc(1)256 }257 }258259 if let Some(bar) = progress_bar.as_ref() {260 bar.finish_and_clear()261 }262263 self.shell_spawning_time = Some(TimingResult {264 time_real: mean(×_real),265 time_user: mean(×_user),266 time_system: mean(×_system),267 });268269 Ok(())270 }271272 fn time_overhead(&self) -> Second {273 self.shell_spawning_time.unwrap().time_real274 }275}276277#[derive(Clone)]278pub struct MockExecutor {279 shell: Option<String>,280}281282impl MockExecutor {283 pub fn new(shell: Option<String>) -> Self {284 MockExecutor { shell }285 }286287 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {288 assert!(sleep_command.as_ref().starts_with("sleep "));289 sleep_command290 .as_ref()291 .trim_start_matches("sleep ")292 .parse::<Second>()293 .unwrap()294 }295}296297impl Executor for MockExecutor {298 fn run_command_and_measure(299 &self,300 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 301why, one step back301 _iteration: BenchmarkIteration,Shrink unsafe blockcactterbefore adoption2e8ce30
lines 302–341why, one step back302 _command_failure_action: Option<CmdFailureAction>,303 ) -> Result<(TimingResult, ExitStatus)> {304 #[cfg(unix)]305 let status = {306 use std::os::unix::process::ExitStatusExt;307 ExitStatus::from_raw(0)308 };309310 #[cfg(windows)]311 let status = {312 use std::os::windows::process::ExitStatusExt;313 ExitStatus::from_raw(0)314 };315316 Ok((317 TimingResult {318 time_real: Self::extract_time(command.get_command_line()),319 time_user: 0.0,320 time_system: 0.0,321 },322 status,323 ))324 }325326 fn calibrate(&mut self) -> Result<()> {327 Ok(())328 }329330 fn time_overhead(&self) -> Second {331 match &self.shell {332 None => 0.0,333 Some(shell) => Self::extract_time(shell),334 }335 }336}337338#[test]339fn test_mock_executor_extract_time() {340 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);341}