executor.rs
This file
Path
src/benchmark/executor.rs
374 lines · 12.0 KiB · Rust
Last changed by
Make memory units availableDavid Peterbefore adoptionf342e1f
History of this fileTake it
The walk stopped after 200 commits: lines older than ed85ac2 point at it.
Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 1–4why, one step back1#[cfg(windows)]2use std::os::windows::process::CommandExt;3use std::process::ExitStatus;4Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 5–6why, one step back5use crate::benchmark::measurement::Measurement;6use crate::benchmark::measurement::Measurements;Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 7–11why, one step back7use crate::command::Command;8use crate::options::{9 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,10};11use crate::output::progress_bar::get_progress_bar;Make memory units availableDavid Peterbefore adoptionf342e1f
line 12why, one step back12use crate::quantity::{second, Information, Quantity, Time};Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 13why, one step back13use crate::timer::execute_and_measure;Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 14–17why, one step back14use crate::util::randomized_environment_offset;1516use anyhow::{bail, Context, Result};17Merge pull request #807 from willcl-ark/expose-run-varDavid Peterbefore adoption30a2b61
line 18why, one step back18#[derive(Clone, Copy)]Add 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}34Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
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,Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 41why, one step back41 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 42why, one step back42 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 43why, one step back43 ) -> Result<Measurement>;Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 44–54why, one step back4445 /// Perform a calibration of this executor. For example,46 /// when running commands through a shell, we need to47 /// measure the shell spawning time separately in order48 /// to subtract it from the full runtime later.49 fn calibrate(&mut self) -> Result<()>;5051 /// Return the time overhead for this executor when52 /// performing a measurement. This should return the time53 /// that is being used in addition to the actual runtime54 /// of the command.Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 55why, one step back55 fn time_overhead(&self) -> Time;Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 56–59why, one step back56}5758fn run_command_and_measure_common(59 mut command: std::process::Command,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 60why, one step back60 iteration: BenchmarkIteration,Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 61–64why, one step back61 command_failure_action: CmdFailureAction,62 command_input_policy: &CommandInputPolicy,63 command_output_policy: &CommandOutputPolicy,64 command_name: &str,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 65why, one step back65) -> Result<Measurement> {Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 66–74why, one step back66 let stdin = command_input_policy.get_stdin()?;67 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;68 command.stdin(stdin).stdout(stdout).stderr(stderr);6970 command.env(71 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",72 randomized_environment_offset::value(),73 );74Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 75–78why, one step back75 if let Some(value) = iteration.to_env_var_value() {76 command.env("HYPERFINE_ITERATION", value);77 }78RefactoringDavid Peterbefore adoption71365c2
line 79why, one step back79 let measurement = execute_and_measure(command)style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 80why, one step back80 .with_context(|| format!("Failed to run command '{command_name}'"))?;Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 81why, one step back81RefactoringDavid Peterbefore adoption71365c2
lines 82–83why, one step back82 if command_failure_action == CmdFailureAction::RaiseError && !measurement.exit_status.success()83 {Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 84–93why, one step back84 let when = match iteration {85 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),86 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),87 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),88 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),89 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),90 };91 bail!(92 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \93 Alternatively, use the '--show-output' option to debug what went wrong.",RefactoringDavid Peterbefore adoption71365c2
line 94why, one step back94 cause=measurement.exit_status.code().map_or(Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 95–96why, one step back95 "The process has been terminated by a signal".into(),96 |c| format!("Command terminated with non-zero exit code {c}")Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 97–102why, one step back9798 let should_fail = match command_failure_action {99 CmdFailureAction::RaiseError => true,100 CmdFailureAction::IgnoreAllFailures => false,101 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {102 // 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 103why, one step back103 if let Some(exit_code) = extract_exit_code(result.exit_status) {Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 104–109why, one step back104 !codes.contains(&exit_code)105 } else {106 // If we can't extract an exit code, treat it as a failure107 true108 }109 }Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 110–111why, one step back110 };111Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 112–122why, one step back112 if should_fail {113 let when = match iteration {114 BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(),115 BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(),116 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),117 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),118 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),119 };120 bail!(121 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \122 Alternatively, use the '--show-output' option to debug what went wrong.",Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 123why, one step back123 cause=result.exit_status.code().map_or(Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 124–129why, one step back124 "The process has been terminated by a signal".into(),125 |c| format!("Command terminated with non-zero exit code {c}")126127 ),128 );129 }Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 130–131why, one step back130 }131RefactoringDavid Peterbefore adoption71365c2
line 132why, one step back132 Ok(measurement)Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 133–144why, one step back133}134135pub struct RawExecutor<'a> {136 options: &'a Options,137}138139impl<'a> RawExecutor<'a> {140 pub fn new(options: &'a Options) -> Self {141 RawExecutor { options }142 }143}144apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 145why, one step back145impl Executor for RawExecutor<'_> {Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 146–148why, one step back146 fn run_command_and_measure(147 &self,148 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 149why, one step back149 iteration: BenchmarkIteration,Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 150why, one step back150 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 151why, one step back151 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 152why, one step back152 ) -> Result<Measurement> {RefactoringDavid Peterbefore adoption71365c2
line 153why, one step back153 run_command_and_measure_common(Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 154why, one step back154 command.get_command()?,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 155why, one step back155 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 156why, one step back156 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 157why, one step back157 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 158why, one step back158 output_policy,Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 159why, one step back159 &command.get_command_line(),RefactoringDavid Peterbefore adoption71365c2
line 160why, one step back160 )Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 161–166why, one step back161 }162163 fn calibrate(&mut self) -> Result<()> {164 Ok(())165 }166Use uomDavid Peterbefore adoption641451a
lines 167–168why, one step back167 fn time_overhead(&self) -> Time {168 Time::zero()Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 169–174why, one step back169 }170}171172pub struct ShellExecutor<'a> {173 options: &'a Options,174 shell: &'a Shell,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 175why, one step back175 shell_spawning_time: Option<Measurement>,Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 176–187why, one step back176}177178impl<'a> ShellExecutor<'a> {179 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {180 ShellExecutor {181 shell,182 options,183 shell_spawning_time: None,184 }185 }186}187apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb
line 188why, one step back188impl Executor for ShellExecutor<'_> {Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 189–191why, one step back189 fn run_command_and_measure(190 &self,191 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 192why, one step back192 iteration: BenchmarkIteration,Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 193why, one step back193 command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 194why, one step back194 output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 195why, one step back195 ) -> Result<Measurement> {Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 196–207why, one step back196 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");197 let mut command_builder = self.shell.command();198 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });199200 // Windows needs special treatment for its behavior on parsing cmd arguments201 if on_windows_cmd {202 #[cfg(windows)]203 command_builder.raw_arg(command.get_command_line());204 } else {205 command_builder.arg(command.get_command_line());206 }207RefactoringDavid Peterbefore adoption71365c2
line 208why, one step back208 let mut measurement = run_command_and_measure_common(Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 209why, one step back209 command_builder,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 210why, one step back210 iteration,Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 211why, one step back211 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 212why, one step back212 &self.options.command_input_policy,Multiple output policiesDavid Peterbefore adoption99d24b7
line 213why, one step back213 output_policy,Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 214–217why, one step back214 &command.get_command_line(),215 )?;216217 // Subtract shell spawning timeUse uomDavid Peterbefore adoption641451a
lines 218–220why, one step back218 fn ensure_non_negative(time: Time) -> Time {219 if time < Time::zero() {220 Time::zero()Switch to unit-safe quantitiesDavid Peterbefore adoptionf9aa299
lines 221–225why, one step back221 } else {222 time223 }224 }225Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 226why, one step back226 if let Some(ref spawning_time) = self.shell_spawning_time {RefactoringDavid Peterbefore adoption71365c2
lines 227–232why, one step back227 measurement.time_wall_clock =228 ensure_non_negative(measurement.time_wall_clock - spawning_time.time_wall_clock);229 measurement.time_user =230 ensure_non_negative(measurement.time_user - spawning_time.time_user);231 measurement.time_system =232 ensure_non_negative(measurement.time_system - spawning_time.time_system);Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 233–234why, one step back233 }234RefactoringDavid Peterbefore adoption71365c2
line 235why, one step back235 Ok(measurement)Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 236–250why, one step back236 }237238 /// Measure the average shell spawning time239 fn calibrate(&mut self) -> Result<()> {240 const COUNT: u64 = 50;241 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {242 Some(get_progress_bar(243 COUNT,244 "Measuring shell spawning time",245 self.options.output_style,246 ))247 } else {248 None249 };250Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 251why, one step back251 let mut measurements = Measurements::default();Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 252–254why, one step back252253 for _ in 0..COUNT {254 // Just run the shell without any commandUnify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 255why, one step back255 let measurement = self.run_command_and_measure(Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 256–258why, one step back256 &Command::new(None, ""),257 BenchmarkIteration::NonBenchmarkRun,258 None,Multiple output policiesDavid Peterbefore adoption99d24b7
line 259why, one step back259 &CommandOutputPolicy::Null,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 260why, one step back260 );Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 261why, one step back261Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 262why, one step back262 match measurement {Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 263–274why, one step back263 Err(_) => {264 let shell_cmd = if cfg!(windows) {265 format!("{} /C \"\"", self.shell)266 } else {267 format!("{} -c \"\"", self.shell)268 };269270 bail!(271 "Could not measure shell execution time. Make sure you can run '{}'.",272 shell_cmd273 );274 }Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 275–276why, one step back275 Ok(result) => {276 measurements.push(result);Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 277–288why, one step back277 }278 }279280 if let Some(bar) = progress_bar.as_ref() {281 bar.inc(1)282 }283 }284285 if let Some(bar) = progress_bar.as_ref() {286 bar.finish_and_clear()287 }288Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 289–294why, one step back289 self.shell_spawning_time = Some(Measurement {290 time_wall_clock: measurements.time_wall_clock_mean(),291 time_user: measurements.time_user_mean(),292 time_system: measurements.time_system_mean(),293 peak_memory_usage: measurements.peak_memory_usage_mean(),294 exit_status: ExitStatus::default(),Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 295–299why, one step back295 });296297 Ok(())298 }299Use uomDavid Peterbefore adoption641451a
line 300why, one step back300 fn time_overhead(&self) -> Time {Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
line 301why, one step back301 self.shell_spawning_time.as_ref().unwrap().time_wall_clockBump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 302–314why, one step back302 }303}304305#[derive(Clone)]306pub struct MockExecutor {307 shell: Option<String>,308}309310impl MockExecutor {311 pub fn new(shell: Option<String>) -> Self {312 MockExecutor { shell }313 }314Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 315why, one step back315 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Time {Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 316why, one step back316 assert!(sleep_command.as_ref().starts_with("sleep "));Remove alternative constructorsDavid Peterbefore adoption3494c8a
line 317why, one step back317 Time::new::<second>(Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
lines 318–323why, one step back318 sleep_command319 .as_ref()320 .trim_start_matches("sleep ")321 .parse::<f64>()322 .unwrap(),323 )Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 324–330why, one step back324 }325}326327impl Executor for MockExecutor {328 fn run_command_and_measure(329 &self,330 command: &Command<'_>,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 331why, one step back331 _iteration: BenchmarkIteration,Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 332why, one step back332 _command_failure_action: Option<CmdFailureAction>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 333why, one step back333 _output_policy: &CommandOutputPolicy,Merge pull request #954 from sharkdp/codex/remove-statisticalDavid Peterbefore adoption750fe11
line 334why, one step back334 ) -> Result<Measurement> {Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 335why, one step back335 #[cfg(unix)]Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 336why, one step back336 let exit_status = {Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 337–341why, one step back337 use std::os::unix::process::ExitStatusExt;338 ExitStatus::from_raw(0)339 };340341 #[cfg(windows)]Merge pull request #958 from sharkdp/codex/measurements-collectionDavid Peterbefore adoption16e23a1
line 342why, one step back342 let exit_status = {Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 343–346why, one step back343 use std::os::windows::process::ExitStatusExt;344 ExitStatus::from_raw(0)345 };346Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 347–348why, one step back347 Ok(Measurement {348 time_wall_clock: Self::extract_time(command.get_command_line()),Use uomDavid Peterbefore adoption641451a
lines 349–350why, one step back349 time_user: Time::zero(),350 time_system: Time::zero(),Represent memory usage as f64 as wellDavid Peterbefore adoption6b4e9eb
line 351why, one step back351 peak_memory_usage: Information::zero(),Unify TimingResult/TimerResult/MeasurementDavid Peterbefore adoption42e75c1
lines 352–353why, one step back352 exit_status,353 })Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 354–359why, one step back354 }355356 fn calibrate(&mut self) -> Result<()> {357 Ok(())358 }359Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 360why, one step back360 fn time_overhead(&self) -> Time {Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 361why, one step back361 match &self.shell {Use uomDavid Peterbefore adoption641451a
line 362why, one step back362 None => Time::zero(),Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
lines 363–369why, one step back363 Some(shell) => Self::extract_time(shell),364 }365 }366}367368#[test]369fn test_mock_executor_extract_time() {Use uomDavid Peterbefore adoption641451a
lines 370–371why, one step back370 assert_eq!(371 MockExecutor::extract_time("sleep 0.1"),Remove alternative constructorsDavid Peterbefore adoption3494c8a
line 372why, one step back372 Time::new::<second>(0.1)Use uomDavid Peterbefore adoption641451a
line 373why, one step back373 );Bump serde from 1.0.179 to 1.0.188dependabot[bot]before adoptioned85ac2
line 374why, one step back374}