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 fileTake it
1use std::process::{ExitStatus, Stdio};23use crate::command::Command;4use crate::options::{CmdFailureAction, Options, OutputStyleOption, Shell};5use crate::output::progress_bar::get_progress_bar;6use crate::timer::{execute_and_measure, wall_clock_timer::WallClockTimer};7use crate::util::randomized_environment_offset;8use crate::util::units::Second;910use super::timing_result::TimingResult;1112use anyhow::{bail, Context, Result};13use statistical::mean;1415pub trait Executor {16 /// Run the given command and measure the execution time17 fn run_command_and_measure(18 &self,19 command: &Command<'_>,20 command_failure_action: Option<CmdFailureAction>,21 ) -> Result<(TimingResult, ExitStatus)>;2223 /// 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.27 fn calibrate(&mut self) -> Result<()>;2829 /// Return the time overhead for this executor when30 /// performing a measurement. This should return the time31 /// that is being used in addition to the actual runtime32 /// of the command.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> {61 fn run_command_and_measure(62 &self,63 command: &Command<'_>,64 command_failure_action: Option<CmdFailureAction>,65 ) -> Result<(TimingResult, ExitStatus)> {66 let (stdout, stderr) = self.options.command_output_policy.get_stdout_stderr();6768 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);7980 let wallclock_timer = WallClockTimer::start();81 let result = execute_and_measure(command_builder)82 .with_context(|| format!("Failed to run command '{}'", command.get_command_line()))?;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 command138 let res = self.run_command_and_measure(&Command::new(None, ""), None);139140 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(×_real),171 time_user: mean(×_user),172 time_system: mean(×_system),173 });174175 Ok(())176 }177178 fn time_overhead(&self) -> Second {179 self.shell_spawning_time.unwrap().time_real180 }181}182183#[derive(Clone)]184pub struct MockExecutor {185 shell: Option<String>,186}187188impl MockExecutor {189 pub fn new(shell: Option<String>) -> Self {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}202203impl Executor for MockExecutor {204 fn run_command_and_measure(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 {223 time_real: Self::extract_time(command.get_command_line()),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 {236 match &self.shell {237 None => 0.0,238 Some(shell) => Self::extract_time(shell),239 }240 }241}242243#[test]244fn test_mock_executor_extract_time() {245 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);246}