Skip to content
Myr

executor.rs

This file

Path

src/benchmark/executor.rs

228 lines · 6.6 KiB · Rust

Last changed by

Refactor timer moduleDavid Peterbefore adoptiondefafdf

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::util::units::Second;910use super::timing_result::TimingResult;1112use anyhow::{bail, Result};13use statistical::mean;1415pub trait Executor {16    fn time_command(17        &self,18        command: &Command<'_>,19        command_failure_action: Option<CmdFailureAction>,20    ) -> Result<(TimingResult, ExitStatus)>;2122    fn calibrate(&mut self) -> Result<()>;2324    fn time_overhead(&self) -> Second;25}2627pub struct ShellExecutor<'a> {28    options: &'a Options,29    shell: &'a Shell,30    shell_spawning_time: Option<TimingResult>,31}3233impl<'a> ShellExecutor<'a> {34    fn subtract_shell_spawning_time(&self, time: Second, shell_spawning_time: Second) -> Second {35        if time < shell_spawning_time {36            0.037        } else {38            time - shell_spawning_time39        }40    }4142    pub fn new(shell: &'a Shell, options: &'a Options) -> Self {43        ShellExecutor {44            shell,45            options,46            shell_spawning_time: None,47        }48    }49}5051impl<'a> Executor for ShellExecutor<'a> {52    /// Run the given shell command and measure the execution time53    fn time_command(54        &self,55        command: &Command<'_>,56        command_failure_action: Option<CmdFailureAction>,57    ) -> Result<(TimingResult, ExitStatus)> {58        let (stdout, stderr) = match self.options.command_output_policy {59            CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),60            CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),61        };6263        let wallclock_timer = WallClockTimer::start();64        let result = execute_and_time(stdout, stderr, &command.get_shell_command(), self.shell)?;65        let mut time_real = wallclock_timer.stop();6667        let mut time_user = result.user_time;68        let mut time_system = result.system_time;6970        if command_failure_action.unwrap_or(self.options.command_failure_action)71            == CmdFailureAction::RaiseError72            && !result.status.success()73        {74            bail!(75                "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \76                Alternatively, use the '--show-output' option to debug what went wrong.",77                result.status.code().map_or(78                    "The process has been terminated by a signal".into(),79                    |c| format!("Command terminated with non-zero exit code: {}", c)80                )81            );82        }8384        // Subtract shell spawning time85        if let Some(spawning_time) = self.shell_spawning_time {86            time_real = self.subtract_shell_spawning_time(time_real, spawning_time.time_real);87            time_user = self.subtract_shell_spawning_time(time_user, spawning_time.time_user);88            time_system = self.subtract_shell_spawning_time(time_system, spawning_time.time_system);89        }9091        Ok((92            TimingResult {93                time_real,94                time_user,95                time_system,96            },97            result.status,98        ))99    }100101    /// Measure the average shell spawning time102    fn calibrate(&mut self) -> Result<()> {103        const COUNT: u64 = 50;104        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {105            Some(get_progress_bar(106                COUNT,107                "Measuring shell spawning time",108                self.options.output_style,109            ))110        } else {111            None112        };113114        let mut times_real: Vec<Second> = vec![];115        let mut times_user: Vec<Second> = vec![];116        let mut times_system: Vec<Second> = vec![];117118        for _ in 0..COUNT {119            // Just run the shell without any command120            let res = self.time_command(&Command::new(None, ""), None);121122            match res {123                Err(_) => {124                    let shell_cmd = if cfg!(windows) {125                        format!("{} /C \"\"", self.shell)126                    } else {127                        format!("{} -c \"\"", self.shell)128                    };129130                    bail!(131                        "Could not measure shell execution time. Make sure you can run '{}'.",132                        shell_cmd133                    );134                }135                Ok((r, _)) => {136                    times_real.push(r.time_real);137                    times_user.push(r.time_user);138                    times_system.push(r.time_system);139                }140            }141142            if let Some(bar) = progress_bar.as_ref() {143                bar.inc(1)144            }145        }146147        if let Some(bar) = progress_bar.as_ref() {148            bar.finish_and_clear()149        }150151        self.shell_spawning_time = Some(TimingResult {152            time_real: mean(&times_real),153            time_user: mean(&times_user),154            time_system: mean(&times_system),155        });156157        Ok(())158    }159160    fn time_overhead(&self) -> Second {161        self.shell_spawning_time.unwrap().time_real162    }163}164165#[derive(Clone)]166pub struct MockExecutor {167    shell: Option<String>,168}169170impl MockExecutor {171    pub fn new(shell: Option<String>) -> Self {172        MockExecutor { shell }173    }174175    fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second {176        assert!(sleep_command.as_ref().starts_with("sleep "));177        sleep_command178            .as_ref()179            .trim_start_matches("sleep ")180            .parse::<Second>()181            .unwrap()182    }183}184185impl Executor for MockExecutor {186    fn time_command(187        &self,188        command: &Command<'_>,189        _command_failure_action: Option<CmdFailureAction>,190    ) -> Result<(TimingResult, ExitStatus)> {191        #[cfg(unix)]192        let status = {193            use std::os::unix::process::ExitStatusExt;194            ExitStatus::from_raw(0)195        };196197        #[cfg(windows)]198        let status = {199            use std::os::windows::process::ExitStatusExt;200            ExitStatus::from_raw(0)201        };202203        Ok((204            TimingResult {205                time_real: Self::extract_time(command.get_shell_command()),206                time_user: 0.0,207                time_system: 0.0,208            },209            status,210        ))211    }212213    fn calibrate(&mut self) -> Result<()> {214        Ok(())215    }216217    fn time_overhead(&self) -> Second {218        match &self.shell {219            None => 0.0,220            Some(shell) => Self::extract_time(shell),221        }222    }223}224225#[test]226fn test_mock_executor_extract_time() {227    assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1);228}