Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

245 lines · 7.3 KiB · Rust

Last changed by

Extract common functionalityDavid Peterbefore adoption308bf5c

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;

Extract common functionalityDavid Peterbefore adoption308bf5c

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

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Extract common functionalityDavid Peterbefore adoption308bf5c

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

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–35why, one step back
33 fn time_overhead(&self) -> Second;
34}35

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 36–66why, one step back
36fn run_command_and_measure_common(
37 mut command: std::process::Command,38 command_failure_action: CmdFailureAction,39 command_output_policy: CommandOutputPolicy,40 command_name: &str,41) -> Result<TimerResult> {42 let (stdout, stderr) = command_output_policy.get_stdout_stderr();43 command.stdin(Stdio::null()).stdout(stdout).stderr(stderr);4445 command.env(46 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",47 randomized_environment_offset::value(),48 );4950 let result = execute_and_measure(command)51 .with_context(|| format!("Failed to run command '{}'", command_name))?;5253 if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {54 bail!(55 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \56 Alternatively, use the '--show-output' option to debug what went wrong.",57 result.status.code().map_or(58 "The process has been terminated by a signal".into(),59 |c| format!("Command terminated with non-zero exit code: {}", c)60 )61 );62 }6364 Ok(result)65}66

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 67–83why, one step back
67pub struct ShellExecutor<'a> {
68 options: &'a Options,69 shell: &'a Shell,70 shell_spawning_time: Option<TimingResult>,71}7273impl<'a> ShellExecutor<'a> {74 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {75 ShellExecutor {76 shell,77 options,78 shell_spawning_time: None,79 }80 }81}8283impl<'a> Executor for ShellExecutor<'a> {

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 84why, one step back
84 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 85–88why, one step back
85 &self,
86 command: &Command<'_>,87 command_failure_action: Option<CmdFailureAction>,88 ) -> Result<(TimingResult, ExitStatus)> {

Move custom functionality to executorDavid Peterbefore adoption1f3943e

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

Change argument orderDavid Peterbefore adoptione001530

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

Move custom functionality to executorDavid Peterbefore adoption1f3943e

line 93why, one step back
93

Extract common functionalityDavid Peterbefore adoption308bf5c

lines 94–99why, one step back
94 let mut result = run_command_and_measure_common(
95 command_builder,96 command_failure_action.unwrap_or(self.options.command_failure_action),97 self.options.command_output_policy,98 &command.get_command_line(),99 )?;

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 100–102why, one step back
100
101 // Subtract shell spawning time102 if let Some(spawning_time) = self.shell_spawning_time {

SimplifyDavid Peterbefore adoptionf19223b

lines 103–105why, one step back
103 result.time_real = (result.time_real - spawning_time.time_real).max(0.0);
104 result.time_user = (result.time_user - spawning_time.time_user).max(0.0);105 result.time_system = (result.time_system - spawning_time.time_system).max(0.0);

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 106–109why, one step back
106 }
107108 Ok((109 TimingResult {

SimplifyDavid Peterbefore adoptionf19223b

lines 110–112why, one step back
110 time_real: result.time_real,
111 time_user: result.time_user,112 time_system: result.time_system,

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 113–136why, one step back
113 },
114 result.status,115 ))116 }117118 /// Measure the average shell spawning time119 fn calibrate(&mut self) -> Result<()> {120 const COUNT: u64 = 50;121 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {122 Some(get_progress_bar(123 COUNT,124 "Measuring shell spawning time",125 self.options.output_style,126 ))127 } else {128 None129 };130131 let mut times_real: Vec<Second> = vec![];132 let mut times_user: Vec<Second> = vec![];133 let mut times_system: Vec<Second> = vec![];134135 for _ in 0..COUNT {136 // Just run the shell without any command

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 138–182why, one step back
138
139 match res {140 Err(_) => {141 let shell_cmd = if cfg!(windows) {142 format!("{} /C \"\"", self.shell)143 } else {144 format!("{} -c \"\"", self.shell)145 };146147 bail!(148 "Could not measure shell execution time. Make sure you can run '{}'.",149 shell_cmd150 );151 }152 Ok((r, _)) => {153 times_real.push(r.time_real);154 times_user.push(r.time_user);155 times_system.push(r.time_system);156 }157 }158159 if let Some(bar) = progress_bar.as_ref() {160 bar.inc(1)161 }162 }163164 if let Some(bar) = progress_bar.as_ref() {165 bar.finish_and_clear()166 }167168 self.shell_spawning_time = Some(TimingResult {169 time_real: mean(&times_real),170 time_user: mean(&times_user),171 time_system: mean(&times_system),172 });173174 Ok(())175 }176177 fn time_overhead(&self) -> Second {178 self.shell_spawning_time.unwrap().time_real179 }180}181182#[derive(Clone)]

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

line 203why, one step back
203 fn run_command_and_measure(

Add debug/mock modeDavid Peterbefore adoption6f51232

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

Rename to get_command_lineDavid Peterbefore adoption826449b

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

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 223–234why, one step back
223 time_user: 0.0,
224 time_system: 0.0,225 },226 status,227 ))228 }229230 fn calibrate(&mut self) -> Result<()> {231 Ok(())232 }233234 fn time_overhead(&self) -> Second {

Proper shell overhead computationDavid Peterbefore adoption6887835

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

Add debug/mock modeDavid Peterbefore adoption6f51232

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