Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

229 lines · 6.7 KiB · Rust

Last changed by

Remove commentDavid Peterbefore adoptioncb6f2f7

History of this file

Take it

1use 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    fn subtract_shell_spawning_time(&self, time: Second, shell_spawning_time: Second) -> Second {36        if time < shell_spawning_time {37            0.038        } else {39            time - shell_spawning_time40        }41    }4243    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> {53    /// Run the given shell command and measure the execution time54    fn time_command(55        &self,56        command: &Command<'_>,57        command_failure_action: Option<CmdFailureAction>,58    ) -> Result<(TimingResult, ExitStatus)> {59        let (stdout, stderr) = match self.options.command_output_policy {60            CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),61            CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),62        };6364        let wallclock_timer = WallClockTimer::start();65        let result = execute_and_time(stdout, stderr, &command.get_shell_command(), &self.shell)?;66        let mut time_real = wallclock_timer.stop();6768        let mut time_user = result.user_time;69        let mut time_system = result.system_time;7071        if command_failure_action.unwrap_or(self.options.command_failure_action)72            == CmdFailureAction::RaiseError73            && !result.status.success()74        {75            bail!(76                "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \77                Alternatively, use the '--show-output' option to debug what went wrong.",78                result.status.code().map_or(79                    "The process has been terminated by a signal".into(),80                    |c| format!("Command terminated with non-zero exit code: {}", c)81                )82            );83        }8485        // Subtract shell spawning time86        if let Some(spawning_time) = self.shell_spawning_time {87            time_real = self.subtract_shell_spawning_time(time_real, spawning_time.time_real);88            time_user = self.subtract_shell_spawning_time(time_user, spawning_time.time_user);89            time_system = self.subtract_shell_spawning_time(time_system, spawning_time.time_system);90        }9192        Ok((93            TimingResult {94                time_real,95                time_user,96                time_system,97            },98            result.status,99        ))100    }101102    /// Measure the average shell spawning time103    fn calibrate(&mut self) -> Result<()> {104        const COUNT: u64 = 50;105        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {106            Some(get_progress_bar(107                COUNT,108                "Measuring shell spawning time",109                self.options.output_style,110            ))111        } else {112            None113        };114115        let mut times_real: Vec<Second> = vec![];116        let mut times_user: Vec<Second> = vec![];117        let mut times_system: Vec<Second> = vec![];118119        for _ in 0..COUNT {120            // Just run the shell without any command121            let res = self.time_command(&Command::new(None, ""), None);122123            match res {124                Err(_) => {125                    let shell_cmd = if cfg!(windows) {126                        format!("{} /C \"\"", self.shell)127                    } else {128                        format!("{} -c \"\"", self.shell)129                    };130131                    bail!(132                        "Could not measure shell execution time. Make sure you can run '{}'.",133                        shell_cmd134                    );135                }136                Ok((r, _)) => {137                    times_real.push(r.time_real);138                    times_user.push(r.time_user);139                    times_system.push(r.time_system);140                }141            }142143            if let Some(bar) = progress_bar.as_ref() {144                bar.inc(1)145            }146        }147148        if let Some(bar) = progress_bar.as_ref() {149            bar.finish_and_clear()150        }151152        self.shell_spawning_time = Some(TimingResult {153            time_real: mean(&times_real),154            time_user: mean(&times_user),155            time_system: mean(&times_system),156        });157158        Ok(())159    }160161    fn time_overhead(&self) -> Second {162        self.shell_spawning_time.unwrap().time_real163    }164}165166#[derive(Clone)]167pub struct MockExecutor {168    shell: Option<String>,169}170171impl MockExecutor {172    pub fn new(shell: Option<String>) -> Self {173        MockExecutor { shell }174    }175176    fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {177        assert!(sleep_command.as_ref().starts_with("sleep "));178        sleep_command179            .as_ref()180            .trim_start_matches("sleep ")181            .parse::<Second>()182            .unwrap()183    }184}185186impl Executor for MockExecutor {187    fn time_command(188        &self,189        command: &Command<'_>,190        _command_failure_action: Option<CmdFailureAction>,191    ) -> Result<(TimingResult, ExitStatus)> {192        #[cfg(unix)]193        let status = {194            use std::os::unix::process::ExitStatusExt;195            ExitStatus::from_raw(0)196        };197198        #[cfg(windows)]199        let status = {200            use std::os::windows::process::ExitStatusExt;201            ExitStatus::from_raw(0)202        };203204        Ok((205            TimingResult {206                time_real: Self::extract_time(command.get_shell_command()),207                time_user: 0.0,208                time_system: 0.0,209            },210            status,211        ))212    }213214    fn calibrate(&mut self) -> Result<()> {215        Ok(())216    }217218    fn time_overhead(&self) -> Second {219        match &self.shell {220            None => 0.0,221            Some(shell) => Self::extract_time(shell),222        }223    }224}225226#[test]227fn test_mock_executor_extract_time() {228    assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);229}