executor.rs
This file
Path
src/benchmark/executor.rs
345 lines · 10.6 KiB · Rust
Last changed by
Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
History of this fileTake it
The walk stopped after 200 commits: lines older than e4790ab 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;Change error messageDavid Peterbefore adoptione4790ab
lines 3–9why, one step back3use std::process::ExitStatus;45use crate::command::Command;6use crate::options::{7 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,8};9use crate::output::progress_bar::get_progress_bar;Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 10why, one step back10use crate::timer::execute_and_measure;Change error messageDavid Peterbefore adoptione4790ab
lines 11–13why, one step back11use crate::util::randomized_environment_offset;12use crate::util::units::Second;13Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 14why, one step back14use super::measurement::{Measurement, Measurements};Change error messageDavid Peterbefore adoptione4790ab
lines 15–17why, one step back1516use anyhow::{bail, Context, Result};17Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 18–33why, one step back18pub enum BenchmarkIteration {19 NonBenchmarkRun,20 Warmup(u64),21 Benchmark(u64),22}2324impl BenchmarkIteration {25 pub fn to_env_var_value(&self) -> Option<String> {26 match self {27 BenchmarkIteration::NonBenchmarkRun => None,28 BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)),29 BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)),30 }31 }32}33Change error messageDavid Peterbefore adoptione4790ab
lines 34–38why, one step back34pub trait Executor {35 /// Run the given command and measure the execution time36 fn run_command_and_measure(37 &self,38 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 39why, one step back39 iteration: BenchmarkIteration,Change error messageDavid Peterbefore adoptione4790ab
line 40why, one step back40 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 41why, one step back41 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 42why, one step back42 ) -> Result<Measurement>;Change error messageDavid Peterbefore adoptione4790ab
lines 43–58why, one step back4344 /// 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,Change error messageDavid Peterbefore adoptione4790ab
lines 60–63why, one step back60 command_failure_action: CmdFailureAction,61 command_input_policy: &CommandInputPolicy,62 command_output_policy: &CommandOutputPolicy,63 command_name: &str,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 64why, one step back64) -> Result<Measurement> {Change error messageDavid Peterbefore adoptione4790ab
lines 65–73why, one step back65 let stdin = command_input_policy.get_stdin()?;66 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;67 command.stdin(stdin).stdout(stdout).stderr(stderr);6869 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 }77Change error messageDavid Peterbefore adoptione4790ab
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}'"))?;Change error messageDavid Peterbefore adoptione4790ab
line 80why, one step back80Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 81why, one step back81 if !result.exit_status.success() {Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 82–88why, one step back82 use crate::util::exit_code::extract_exit_code;8384 let should_fail = match command_failure_action {85 CmdFailureAction::RaiseError => true,86 CmdFailureAction::IgnoreAllFailures => false,87 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {88 // Only fail if the exit code is not in the list of codes to ignoreMerge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 89why, one step back89 if let Some(exit_code) = extract_exit_code(result.exit_status) {Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 90–95why, one step back90 !codes.contains(&exit_code)91 } else {92 // If we can't extract an exit code, treat it as a failure93 true94 }95 }Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 96–97why, one step back96 };97Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 98–108why, one step back98 if should_fail {99 let when = match iteration {100 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),101 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),102 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),103 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),104 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),105 };106 bail!(107 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \108 Alternatively, use the '--show-output' option to debug what went wrong.",Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 109why, one step back109 cause=result.exit_status.code().map_or(Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 110–115why, one step back110 "The process has been terminated by a signal".into(),111 |c| format!("Command terminated with non-zero exit code {c}")112113 ),114 );115 }Change error messageDavid Peterbefore adoptione4790ab
lines 116–130why, one step back116 }117118 Ok(result)119}120121pub struct RawExecutor<'a> {122 options: &'a Options,123}124125impl<'a> RawExecutor<'a> {126 pub fn new(options: &'a Options) -> Self {127 RawExecutor { options }128 }129}130apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 131why, one step back131impl Executor for RawExecutor<'_> {Change error messageDavid Peterbefore adoptione4790ab
lines 132–134why, one step back132 fn run_command_and_measure(133 &self,134 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 135why, one step back135 iteration: BenchmarkIteration,Change error messageDavid Peterbefore adoptione4790ab
line 136why, one step back136 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 137why, one step back137 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
lines 138–139why, one step back138 ) -> Result<Measurement> {139 run_command_and_measure_common(Change error messageDavid Peterbefore adoptione4790ab
line 140why, one step back140 command.get_command()?,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 141why, one step back141 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 142why, one step back142 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),Change error messageDavid Peterbefore adoptione4790ab
line 143why, one step back143 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 144why, one step back144 output_policy,Change error messageDavid Peterbefore adoptione4790ab
line 145why, one step back145 &command.get_command_line(),Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 146why, one step back146 )Change error messageDavid Peterbefore adoptione4790ab
lines 147–160why, one step back147 }148149 fn calibrate(&mut self) -> Result<()> {150 Ok(())151 }152153 fn time_overhead(&self) -> Second {154 0.0155 }156}157158pub struct ShellExecutor<'a> {159 options: &'a Options,160 shell: &'a Shell,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 161why, one step back161 shell_spawning_time: Option<Measurement>,Change error messageDavid Peterbefore adoptione4790ab
lines 162–173why, one step back162}163164impl<'a> ShellExecutor<'a> {165 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {166 ShellExecutor {167 shell,168 options,169 shell_spawning_time: None,170 }171 }172}173apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 174why, one step back174impl Executor for ShellExecutor<'_> {Change error messageDavid Peterbefore adoptione4790ab
lines 175–177why, one step back175 fn run_command_and_measure(176 &self,177 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 178why, one step back178 iteration: BenchmarkIteration,Change error messageDavid Peterbefore adoptione4790ab
line 179why, one step back179 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 180why, one step back180 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 181why, one step back181 ) -> Result<Measurement> { bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 182why, one step back182 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");Change error messageDavid Peterbefore adoptione4790ab
line 183why, one step back183 let mut command_builder = self.shell.command();fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
line 184why, one step back184 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" }); bug: quoting failure on windows-platform (#296)Pedro Witzelbefore adoptionbece2ea
line 185why, one step back185fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 186–187why, one step back186 // Windows needs special treatment for its behavior on parsing cmd arguments187 if on_windows_cmd {cfg: adding more pre-processing for windows-only parserPedro Witzelbefore adoptionae9b0bb
line 188why, one step back188 #[cfg(windows)]fmt: apply cargo fmt suggestionsPedro Witzelbefore adoptionc2f99e5
lines 189–192why, one step back189 command_builder.raw_arg(command.get_command_line());190 } else {191 command_builder.arg(command.get_command_line());192 }Change error messageDavid Peterbefore adoptione4790ab
lines 193–195why, one step back193194 let mut result = run_command_and_measure_common(195 command_builder,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 196why, one step back196 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 197why, one step back197 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),Change error messageDavid Peterbefore adoptione4790ab
line 198why, one step back198 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 199why, one step back199 output_policy,Change error messageDavid Peterbefore adoptione4790ab
lines 200–204why, one step back200 &command.get_command_line(),201 )?;202203 // Subtract shell spawning time204 if let Some(spawning_time) = self.shell_spawning_time {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
lines 205–206why, one step back205 result.time_wall_clock =206 (result.time_wall_clock - spawning_time.time_wall_clock).max(0.0);Change error messageDavid Peterbefore adoptione4790ab
lines 207–210why, one step back207 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);208 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);209 }210Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 211why, one step back211 Ok(result)Change error messageDavid Peterbefore adoptione4790ab
lines 212–226why, one step back212 }213214 /// Measure the average shell spawning time215 fn calibrate(&mut self) -> Result<()> {216 const COUNT: u64 = 50;217 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {218 Some(get_progress_bar(219 COUNT,220 "Measuring shell spawning time",221 self.options.output_style,222 ))223 } else {224 None225 };226Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 227why, one step back227 let mut measurements = Measurements::default();Change error messageDavid Peterbefore adoptione4790ab
lines 228–230why, one step back228229 for _ in 0..COUNT {230 // Just run the shell without any commandAdd iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 231–234why, one step back231 let res = self.run_command_and_measure(232 &Command::new(None, ""),233 BenchmarkIteration::NonBenchmarkRun,234 None,Multiple output policiesDavid Peterbefore adoption99d24b7
line 235why, one step back235 &CommandOutputPolicy::Null,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 236why, one step back236 );Change error messageDavid Peterbefore adoptione4790ab
lines 237–250why, one step back237238 match res {239 Err(_) => {240 let shell_cmd = if cfg!(windows) {241 format!("{} /C \"\"", self.shell)242 } else {243 format!("{} -c \"\"", self.shell)244 };245246 bail!(247 "Could not measure shell execution time. Make sure you can run '{}'.",248 shell_cmd249 );250 }Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 251why, one step back251 Ok(r) => {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 252why, one step back252 measurements.push(r);Change error messageDavid Peterbefore adoptione4790ab
lines 253–264why, one step back253 }254 }255256 if let Some(bar) = progress_bar.as_ref() {257 bar.inc(1)258 }259 }260261 if let Some(bar) = progress_bar.as_ref() {262 bar.finish_and_clear()263 }264Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 265why, one step back265 self.shell_spawning_time = Some(Measurement {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
lines 266–270why, one step back266 time_wall_clock: measurements.time_wall_clock_mean(),267 time_user: measurements.time_user_mean(),268 time_system: measurements.time_system_mean(),269 peak_memory_usage: 0,270 exit_status: ExitStatus::default(),Change error messageDavid Peterbefore adoptione4790ab
lines 271–276why, one step back271 });272273 Ok(())274 }275276 fn time_overhead(&self) -> Second {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 277why, one step back277 self.shell_spawning_time.unwrap().time_wall_clockChange error messageDavid Peterbefore adoptione4790ab
lines 278–304why, one step back278 }279}280281#[derive(Clone)]282pub struct MockExecutor {283 shell: Option<String>,284}285286impl MockExecutor {287 pub fn new(shell: Option<String>) -> Self {288 MockExecutor { shell }289 }290291 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {292 assert!(sleep_command.as_ref().starts_with("sleep "));293 sleep_command294 .as_ref()295 .trim_start_matches("sleep ")296 .parse::<Second>()297 .unwrap()298 }299}300301impl Executor for MockExecutor {302 fn run_command_and_measure(303 &self,304 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 305why, one step back305 _iteration: BenchmarkIteration,Change error messageDavid Peterbefore adoptione4790ab
line 306why, one step back306 _command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 307why, one step back307 _output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 308why, one step back308 ) -> Result<Measurement> {Change error messageDavid Peterbefore adoptione4790ab
line 309why, one step back309 #[cfg(unix)]Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 310why, one step back310 let exit_status = {Change error messageDavid Peterbefore adoptione4790ab
lines 311–315why, one step back311 use std::os::unix::process::ExitStatusExt;312 ExitStatus::from_raw(0)313 };314315 #[cfg(windows)]Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 316why, one step back316 let exit_status = {Change error messageDavid Peterbefore adoptione4790ab
lines 317–320why, one step back317 use std::os::windows::process::ExitStatusExt;318 ExitStatus::from_raw(0)319 };320Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 321why, one step back321 Ok(Measurement {Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 322why, one step back322 time_wall_clock: Self::extract_time(command.get_command_line()),Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
lines 323–324why, one step back323 time_user: 0.0,324 time_system: 0.0,Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
lines 325–326why, one step back325 peak_memory_usage: 0,326 exit_status,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 327why, one step back327 })Change error messageDavid Peterbefore adoptione4790ab
lines 328–345why, one step back328 }329330 fn calibrate(&mut self) -> Result<()> {331 Ok(())332 }333334 fn time_overhead(&self) -> Second {335 match &self.shell {336 None => 0.0,337 Some(shell) => Self::extract_time(shell),338 }339 }340}341342#[test]343fn test_mock_executor_extract_time() {344 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);345}