Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

233 lines · 7.0 KiB · Rust

Last changed by

SimplifyDavid Peterbefore adoptionf19223b

History of this file

Take it

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 1–3why, one step back
1use std::process::{ExitStatus, Stdio};
23use crate::command::Command;

Move Stdio extraction to enumDavid Peterbefore adoption9b8f2a9

line 4why, one step back
4use crate::options::{CmdFailureAction, Options, OutputStyleOption, Shell};

Add debug/mock modeDavid Peterbefore adoption6f51232

line 5why, one step back
5use crate::output::progress_bar::get_progress_bar;

Move wall clock timer into execute_and_measureDavid Peterbefore adoption55f0ef6

line 6why, one step back
6use crate::timer::execute_and_measure;

Move custom functionality to executorDavid Peterbefore adoption1f3943e

line 7why, one step back
7use crate::util::randomized_environment_offset;

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 8–11why, one step back
8use crate::util::units::Second;
910use super::timing_result::TimingResult;11

Further simplify execute_and_measureDavid Peterbefore adoptione1da8ba

line 12why, one step back
12use anyhow::{bail, Context, Result};

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 13–15why, one step back
13use statistical::mean;
1415pub trait Executor {

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

lines 16–17why, one step back
16 /// Run the given command and measure the execution time
17 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 18–22why, one step back
18 &self,
19 command: &Command<'_>,20 command_failure_action: Option<CmdFailureAction>,21 ) -> Result<(TimingResult, ExitStatus)>;22

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

lines 23–26why, one step back
23 /// Perform a calibration of this executor. For example,
24 /// when running commands through a shell, we need to25 /// measure the shell spawning time separately in order26 /// to subtract it from the full runtime later.

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 27–28why, one step back
27 fn calibrate(&mut self) -> Result<()>;
28

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

lines 29–32why, one step back
29 /// Return the time overhead for this executor when
30 /// performing a measurement. This should return the time31 /// that is being used in addition to the actual runtime32 /// of the command.

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 33–52why, one step back
33 fn time_overhead(&self) -> Second;
34}3536pub struct ShellExecutor<'a> {37 options: &'a Options,38 shell: &'a Shell,39 shell_spawning_time: Option<TimingResult>,40}4142impl<'a> ShellExecutor<'a> {43 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {44 ShellExecutor {45 shell,46 options,47 shell_spawning_time: None,48 }49 }50}5152impl<'a> Executor for ShellExecutor<'a> {

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 53why, one step back
53 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 54–57why, one step back
54 &self,
55 command: &Command<'_>,56 command_failure_action: Option<CmdFailureAction>,57 ) -> Result<(TimingResult, ExitStatus)> {

Move Stdio extraction to enumDavid Peterbefore adoption9b8f2a9

line 58why, one step back
58 let (stdout, stderr) = self.options.command_output_policy.get_stdout_stderr();

Add debug/mock modeDavid Peterbefore adoption6f51232

line 59why, one step back
59

Move custom functionality to executorDavid Peterbefore adoption1f3943e

lines 60–61why, one step back
60 let mut command_builder = self.shell.command();
61 command_builder

Change argument orderDavid Peterbefore adoptione001530

lines 62–64why, one step back
62 .stdin(Stdio::null())
63 .stdout(stdout)64 .stderr(stderr)

Move custom functionality to executorDavid Peterbefore adoption1f3943e

lines 65–68why, one step back
65 .env(
66 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",67 randomized_environment_offset::value(),68 )

Change argument orderDavid Peterbefore adoptione001530

lines 69–70why, one step back
69 .arg(if cfg!(windows) { "/C" } else { "-c" })
70 .arg(command.get_command_line());

Move custom functionality to executorDavid Peterbefore adoption1f3943e

line 71why, one step back
71

SimplifyDavid Peterbefore adoptionf19223b

line 72why, one step back
72 let mut result = execute_and_measure(command_builder)

Further simplify execute_and_measureDavid Peterbefore adoptione1da8ba

line 73why, one step back
73 .with_context(|| format!("Failed to run command '{}'", command.get_command_line()))?;

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 74–90why, one step back
74
75 if command_failure_action.unwrap_or(self.options.command_failure_action)76 == CmdFailureAction::RaiseError77 && !result.status.success()78 {79 bail!(80 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \81 Alternatively, use the '--show-output' option to debug what went wrong.",82 result.status.code().map_or(83 "The process has been terminated by a signal".into(),84 |c| format!("Command terminated with non-zero exit code: {}", c)85 )86 );87 }8889 // Subtract shell spawning time90 if let Some(spawning_time) = self.shell_spawning_time {

SimplifyDavid Peterbefore adoptionf19223b

lines 91–93why, one step back
91 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);
92 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);93 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 94–97why, one step back
94 }
9596 Ok((97 TimingResult {

SimplifyDavid Peterbefore adoptionf19223b

lines 98–100why, one step back
98 time_real: result.time_real,
99 time_user: result.time_user,100 time_system: result.time_system,

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 101–124why, one step back
101 },
102 result.status,103 ))104 }105106 /// Measure the average shell spawning time107 fn calibrate(&mut self) -> Result<()> {108 const COUNT: u64 = 50;109 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {110 Some(get_progress_bar(111 COUNT,112 "Measuring shell spawning time",113 self.options.output_style,114 ))115 } else {116 None117 };118119 let mut times_real: Vec<Second> = vec![];120 let mut times_user: Vec<Second> = vec![];121 let mut times_system: Vec<Second> = vec![];122123 for _ in 0..COUNT {124 // Just run the shell without any command

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 125why, one step back
125 let res = self.run_command_and_measure(&Command::new(None, ""), None);

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 126–170why, one step back
126
127 match res {128 Err(_) => {129 let shell_cmd = if cfg!(windows) {130 format!("{} /C \"\"", self.shell)131 } else {132 format!("{} -c \"\"", self.shell)133 };134135 bail!(136 "Could not measure shell execution time. Make sure you can run '{}'.",137 shell_cmd138 );139 }140 Ok((r, _)) => {141 times_real.push(r.time_real);142 times_user.push(r.time_user);143 times_system.push(r.time_system);144 }145 }146147 if let Some(bar) = progress_bar.as_ref() {148 bar.inc(1)149 }150 }151152 if let Some(bar) = progress_bar.as_ref() {153 bar.finish_and_clear()154 }155156 self.shell_spawning_time = Some(TimingResult {157 time_real: mean(&times_real),158 time_user: mean(&times_user),159 time_system: mean(&times_system),160 });161162 Ok(())163 }164165 fn time_overhead(&self) -> Second {166 self.shell_spawning_time.unwrap().time_real167 }168}169170#[derive(Clone)]

Proper shell overhead computationDavid Peterbefore adoption6887835

lines 171–172why, one step back
171pub struct MockExecutor {
172 shell: Option<String>,

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 173–174why, one step back
173}
174

Proper shell overhead computationDavid Peterbefore adoption6887835

lines 175–176why, one step back
175impl MockExecutor {
176 pub fn new(shell: Option<String>) -> Self {

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 177–189why, one step back
177 MockExecutor { shell }
178 }179180 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {181 assert!(sleep_command.as_ref().starts_with("sleep "));182 sleep_command183 .as_ref()184 .trim_start_matches("sleep ")185 .parse::<Second>()186 .unwrap()187 }188}189

Proper shell overhead computationDavid Peterbefore adoption6887835

line 190why, one step back
190impl Executor for MockExecutor {

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 191why, one step back
191 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 192–209why, one step back
192 &self,
193 command: &Command<'_>,194 _command_failure_action: Option<CmdFailureAction>,195 ) -> Result<(TimingResult, ExitStatus)> {196 #[cfg(unix)]197 let status = {198 use std::os::unix::process::ExitStatusExt;199 ExitStatus::from_raw(0)200 };201202 #[cfg(windows)]203 let status = {204 use std::os::windows::process::ExitStatusExt;205 ExitStatus::from_raw(0)206 };207208 Ok((209 TimingResult {

Rename to get_command_lineDavid Peterbefore adoption826449b

line 210why, one step back
210 time_real: Self::extract_time(command.get_command_line()),

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 211–222why, one step back
211 time_user: 0.0,
212 time_system: 0.0,213 },214 status,215 ))216 }217218 fn calibrate(&mut self) -> Result<()> {219 Ok(())220 }221222 fn time_overhead(&self) -> Second {

Proper shell overhead computationDavid Peterbefore adoption6887835

lines 223–225why, one step back
223 match &self.shell {
224 None => 0.0,225 Some(shell) => Self::extract_time(shell),

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 226–233why, one step back
226 }
227 }228}229230#[test]231fn test_mock_executor_extract_time() {232 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);233}