executor.rs
This file
Path
src/benchmark/executor.rs
230 lines · 6.8 KiB · Rust
Last changed by
Add debug/mock modeDavid Peterbefore adoption6f51232
History of this fileTake it
Add debug/mock modeDavid Peterbefore adoption6f51232
lines 1–230why, one step back1use std::process::{ExitStatus, Stdio};23use crate::command::Command;4use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};5use crate::output::progress_bar::get_progress_bar;6use crate::shell::execute_and_time;7use crate::timer::wallclocktimer::WallClockTimer;8use crate::timer::{TimerStart, TimerStop};9use crate::util::units::Second;1011use super::timing_result::TimingResult;1213use anyhow::{bail, Result};14use statistical::mean;1516pub trait Executor {17 fn time_command(18 &self,19 command: &Command<'_>,20 command_failure_action: Option<CmdFailureAction>,21 ) -> Result<(TimingResult, ExitStatus)>;2223 fn calibrate(&mut self) -> Result<()>;2425 fn time_overhead(&self) -> Second;26}2728pub struct ShellExecutor<'a> {29 options: &'a Options,30 shell: &'a Shell,31 shell_spawning_time: Option<TimingResult>,32}3334impl<'a> ShellExecutor<'a> {35 /// Correct for shell spawning time36 fn subtract_shell_spawning_time(&self, time: Second, shell_spawning_time: Second) -> Second {37 if time < shell_spawning_time {38 0.039 } else {40 time - shell_spawning_time41 }42 }4344 pub fn new(shell: &'a Shell, options: &'a Options) -> Self {45 ShellExecutor {46 shell,47 options,48 shell_spawning_time: None,49 }50 }51}5253impl<'a> Executor for ShellExecutor<'a> {54 /// Run the given shell command and measure the execution time55 fn time_command(56 &self,57 command: &Command<'_>,58 command_failure_action: Option<CmdFailureAction>,59 ) -> Result<(TimingResult, ExitStatus)> {60 let (stdout, stderr) = match self.options.command_output_policy {61 CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),62 CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),63 };6465 let wallclock_timer = WallClockTimer::start();66 let result = execute_and_time(stdout, stderr, &command.get_shell_command(), &self.shell)?;67 let mut time_real = wallclock_timer.stop();6869 let mut time_user = result.user_time;70 let mut time_system = result.system_time;7172 if command_failure_action.unwrap_or(self.options.command_failure_action)73 == CmdFailureAction::RaiseError74 && !result.status.success()75 {76 bail!(77 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \78 Alternatively, use the '--show-output' option to debug what went wrong.",79 result.status.code().map_or(80 "The process has been terminated by a signal".into(),81 |c| format!("Command terminated with non-zero exit code: {}", c)82 )83 );84 }8586 // Subtract shell spawning time87 if let Some(spawning_time) = self.shell_spawning_time {88 time_real = self.subtract_shell_spawning_time(time_real, spawning_time.time_real);89 time_user = self.subtract_shell_spawning_time(time_user, spawning_time.time_user);90 time_system = self.subtract_shell_spawning_time(time_system, spawning_time.time_system);91 }9293 Ok((94 TimingResult {95 time_real,96 time_user,97 time_system,98 },99 result.status,100 ))101 }102103 /// Measure the average shell spawning time104 fn calibrate(&mut self) -> Result<()> {105 const COUNT: u64 = 50;106 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {107 Some(get_progress_bar(108 COUNT,109 "Measuring shell spawning time",110 self.options.output_style,111 ))112 } else {113 None114 };115116 let mut times_real: Vec<Second> = vec![];117 let mut times_user: Vec<Second> = vec![];118 let mut times_system: Vec<Second> = vec![];119120 for _ in 0..COUNT {121 // Just run the shell without any command122 let res = self.time_command(&Command::new(None, ""), None);123124 match res {125 Err(_) => {126 let shell_cmd = if cfg!(windows) {127 format!("{} /C \"\"", self.shell)128 } else {129 format!("{} -c \"\"", self.shell)130 };131132 bail!(133 "Could not measure shell execution time. Make sure you can run '{}'.",134 shell_cmd135 );136 }137 Ok((r, _)) => {138 times_real.push(r.time_real);139 times_user.push(r.time_user);140 times_system.push(r.time_system);141 }142 }143144 if let Some(bar) = progress_bar.as_ref() {145 bar.inc(1)146 }147 }148149 if let Some(bar) = progress_bar.as_ref() {150 bar.finish_and_clear()151 }152153 self.shell_spawning_time = Some(TimingResult {154 time_real: mean(×_real),155 time_user: mean(×_user),156 time_system: mean(×_system),157 });158159 Ok(())160 }161162 fn time_overhead(&self) -> Second {163 self.shell_spawning_time.unwrap().time_real164 }165}166167#[derive(Clone)]168pub struct MockExecutor<'a> {169 shell: &'a Shell,170}171172impl<'a> MockExecutor<'a> {173 pub fn new(shell: &'a Shell) -> Self {174 MockExecutor { shell }175 }176177 fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {178 assert!(sleep_command.as_ref().starts_with("sleep "));179 sleep_command180 .as_ref()181 .trim_start_matches("sleep ")182 .parse::<Second>()183 .unwrap()184 }185}186187impl<'a> Executor for MockExecutor<'a> {188 fn time_command(189 &self,190 command: &Command<'_>,191 _command_failure_action: Option<CmdFailureAction>,192 ) -> Result<(TimingResult, ExitStatus)> {193 #[cfg(unix)]194 let status = {195 use std::os::unix::process::ExitStatusExt;196 ExitStatus::from_raw(0)197 };198199 #[cfg(windows)]200 let status = {201 use std::os::windows::process::ExitStatusExt;202 ExitStatus::from_raw(0)203 };204205 Ok((206 TimingResult {207 time_real: Self::extract_time(command.get_shell_command()),208 time_user: 0.0,209 time_system: 0.0,210 },211 status,212 ))213 }214215 fn calibrate(&mut self) -> Result<()> {216 Ok(())217 }218219 fn time_overhead(&self) -> Second {220 match self.shell {221 Shell::Default(_) => 0.0,222 Shell::Custom(shell) => Self::extract_time(&shell[0]),223 }224 }225}226227#[test]228fn test_mock_executor_extract_time() {229 assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);230}