Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

246 lines · 7.4 KiB · Rust

Last changed by

Move Stdio extraction to enumDavid Peterbefore adoption9b8f2a9

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 to timer moduleDavid Peterbefore adoption0ffc6d7

line 6why, one step back
6use crate::timer::{execute_and_measure, wall_clock_timer::WallClockTimer};

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–60why, 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 fn subtract_shell_spawning_time(&self, time: Second, shell_spawning_time: Second) -> Second {44 if time < shell_spawning_time {45 0.046 } else {47 time - shell_spawning_time48 }49 }5051 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {52 ShellExecutor {53 shell,54 options,55 shell_spawning_time: None,56 }57 }58}5960impl<'a> Executor for ShellExecutor<'a> {

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 61why, one step back
61 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 62–65why, one step back
62 &self,
63 command: &Command<'_>,64 command_failure_action: Option<CmdFailureAction>,65 ) -> Result<(TimingResult, ExitStatus)> {

Move Stdio extraction to enumDavid Peterbefore adoption9b8f2a9

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

Add debug/mock modeDavid Peterbefore adoption6f51232

line 67why, one step back
67

Move custom functionality to executorDavid Peterbefore adoption1f3943e

lines 68–79why, one step back
68 let mut command_builder = self.shell.command();
69 command_builder70 .arg(if cfg!(windows) { "/C" } else { "-c" })71 .arg(command.get_command_line())72 .env(73 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",74 randomized_environment_offset::value(),75 )76 .stdin(Stdio::null())77 .stdout(stdout)78 .stderr(stderr);79

Add debug/mock modeDavid Peterbefore adoption6f51232

line 80why, one step back
80 let wallclock_timer = WallClockTimer::start();

Further simplify execute_and_measureDavid Peterbefore adoptione1da8ba

lines 81–82why, one step back
81 let result = execute_and_measure(command_builder)
82 .with_context(|| format!("Failed to run command '{}'", command.get_command_line()))?;

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 83–137why, one step back
83 let mut time_real = wallclock_timer.stop();
8485 let mut time_user = result.user_time;86 let mut time_system = result.system_time;8788 if command_failure_action.unwrap_or(self.options.command_failure_action)89 == CmdFailureAction::RaiseError90 && !result.status.success()91 {92 bail!(93 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \94 Alternatively, use the '--show-output' option to debug what went wrong.",95 result.status.code().map_or(96 "The process has been terminated by a signal".into(),97 |c| format!("Command terminated with non-zero exit code: {}", c)98 )99 );100 }101102 // Subtract shell spawning time103 if let Some(spawning_time) = self.shell_spawning_time {104 time_real = self.subtract_shell_spawning_time(time_real, spawning_time.time_real);105 time_user = self.subtract_shell_spawning_time(time_user, spawning_time.time_user);106 time_system = self.subtract_shell_spawning_time(time_system, spawning_time.time_system);107 }108109 Ok((110 TimingResult {111 time_real,112 time_user,113 time_system,114 },115 result.status,116 ))117 }118119 /// Measure the average shell spawning time120 fn calibrate(&mut self) -> Result<()> {121 const COUNT: u64 = 50;122 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {123 Some(get_progress_bar(124 COUNT,125 "Measuring shell spawning time",126 self.options.output_style,127 ))128 } else {129 None130 };131132 let mut times_real: Vec<Second> = vec![];133 let mut times_user: Vec<Second> = vec![];134 let mut times_system: Vec<Second> = vec![];135136 for _ in 0..COUNT {137 // Just run the shell without any command

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 139–183why, one step back
139
140 match res {141 Err(_) => {142 let shell_cmd = if cfg!(windows) {143 format!("{} /C \"\"", self.shell)144 } else {145 format!("{} -c \"\"", self.shell)146 };147148 bail!(149 "Could not measure shell execution time. Make sure you can run '{}'.",150 shell_cmd151 );152 }153 Ok((r, _)) => {154 times_real.push(r.time_real);155 times_user.push(r.time_user);156 times_system.push(r.time_system);157 }158 }159160 if let Some(bar) = progress_bar.as_ref() {161 bar.inc(1)162 }163 }164165 if let Some(bar) = progress_bar.as_ref() {166 bar.finish_and_clear()167 }168169 self.shell_spawning_time = Some(TimingResult {170 time_real: mean(&times_real),171 time_user: mean(&times_user),172 time_system: mean(&times_system),173 });174175 Ok(())176 }177178 fn time_overhead(&self) -> Second {179 self.shell_spawning_time.unwrap().time_real180 }181}182183#[derive(Clone)]

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 186–187why, one step back
186}
187

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 190–202why, one step back
190 MockExecutor { shell }
191 }192193 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {194 assert!(sleep_command.as_ref().starts_with("sleep "));195 sleep_command196 .as_ref()197 .trim_start_matches("sleep ")198 .parse::<Second>()199 .unwrap()200 }201}202

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 204why, one step back
204 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 205–222why, one step back
205 &self,
206 command: &Command<'_>,207 _command_failure_action: Option<CmdFailureAction>,208 ) -> Result<(TimingResult, ExitStatus)> {209 #[cfg(unix)]210 let status = {211 use std::os::unix::process::ExitStatusExt;212 ExitStatus::from_raw(0)213 };214215 #[cfg(windows)]216 let status = {217 use std::os::windows::process::ExitStatusExt;218 ExitStatus::from_raw(0)219 };220221 Ok((222 TimingResult {

Rename to get_command_lineDavid Peterbefore adoption826449b

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 224–235why, one step back
224 time_user: 0.0,
225 time_system: 0.0,226 },227 status,228 ))229 }230231 fn calibrate(&mut self) -> Result<()> {232 Ok(())233 }234235 fn time_overhead(&self) -> Second {

Proper shell overhead computationDavid Peterbefore adoption6887835

lines 236–238why, one step back
236 match &self.shell {
237 None => 0.0,238 Some(shell) => Self::extract_time(shell),

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 239–246why, one step back
239 }
240 }241}242243#[test]244fn test_mock_executor_extract_time() {245 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);246}