Skip to content
Myr

mod.rs

This file

Path

src/benchmark/mod.rs

373 lines · 12.2 KiB · Rust

Last changed by

Rename to run_command_and_measureDavid Peterbefore adoption7c929f7

History of this file

Take it

1pub mod benchmark_result;2pub mod executor;3pub mod relative_speed;4pub mod scheduler;5pub mod timing_result;67use std::cmp;89use crate::command::Command;10use crate::options::{CmdFailureAction, Options, OutputStyleOption};11use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};12use crate::output::format::{format_duration, format_duration_unit};13use crate::output::progress_bar::get_progress_bar;14use crate::output::warnings::Warnings;15use crate::parameter::ParameterNameAndValue;16use crate::util::exit_code::extract_exit_code;17use crate::util::min_max::{max, min};18use crate::util::units::Second;19use benchmark_result::BenchmarkResult;20use timing_result::TimingResult;2122use anyhow::{anyhow, Result};23use colored::*;24use statistical::{mean, median, standard_deviation};2526use self::executor::Executor;2728/// Threshold for warning about fast execution time29pub const MIN_EXECUTION_TIME: Second = 5e-3;3031pub struct Benchmark<'a> {32    number: usize,33    command: &'a Command<'a>,34    options: &'a Options,35    executor: &'a dyn Executor,36}3738impl<'a> Benchmark<'a> {39    pub fn new(40        number: usize,41        command: &'a Command<'a>,42        options: &'a Options,43        executor: &'a dyn Executor,44    ) -> Self {45        Benchmark {46            number,47            command,48            options,49            executor,50        }51    }5253    /// Run setup, cleanup, or preparation commands54    fn run_intermediate_command(55        &self,56        command: &Command<'_>,57        error_output: &'static str,58    ) -> Result<TimingResult> {59        self.executor60            .run_command_and_measure(command, Some(CmdFailureAction::RaiseError))61            .map(|r| r.0)62            .map_err(|_| anyhow!(error_output))63    }6465    /// Run the command specified by `--setup`.66    fn run_setup_command(67        &self,68        parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,69    ) -> Result<TimingResult> {70        let command = self71            .options72            .setup_command73            .as_ref()74            .map(|setup_command| Command::new_parametrized(None, setup_command, parameters));7576        let error_output = "The setup command terminated with a non-zero exit code. \77                            Append ' || true' to the command if you are sure that this can be ignored.";7879        Ok(command80            .map(|cmd| self.run_intermediate_command(&cmd, error_output))81            .transpose()?82            .unwrap_or_default())83    }8485    /// Run the command specified by `--cleanup`.86    fn run_cleanup_command(87        &self,88        parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,89    ) -> Result<TimingResult> {90        let command = self91            .options92            .cleanup_command93            .as_ref()94            .map(|cleanup_command| Command::new_parametrized(None, cleanup_command, parameters));9596        let error_output = "The cleanup command terminated with a non-zero exit code. \97                            Append ' || true' to the command if you are sure that this can be ignored.";9899        Ok(command100            .map(|cmd| self.run_intermediate_command(&cmd, error_output))101            .transpose()?102            .unwrap_or_default())103    }104105    /// Run the command specified by `--prepare`.106    fn run_preparation_command(&self, command: &Command<'_>) -> Result<TimingResult> {107        let error_output = "The preparation command terminated with a non-zero exit code. \108                            Append ' || true' to the command if you are sure that this can be ignored.";109110        self.run_intermediate_command(command, error_output)111    }112113    /// Run the benchmark for a single command114    pub fn run(&self) -> Result<BenchmarkResult> {115        let command_name = self.command.get_name();116        if self.options.output_style != OutputStyleOption::Disabled {117            println!(118                "{}{}: {}",119                "Benchmark ".bold(),120                (self.number + 1).to_string().bold(),121                command_name,122            );123        }124125        let mut times_real: Vec<Second> = vec![];126        let mut times_user: Vec<Second> = vec![];127        let mut times_system: Vec<Second> = vec![];128        let mut exit_codes: Vec<Option<i32>> = vec![];129        let mut all_succeeded = true;130131        let preparation_command = self.options.preparation_command.as_ref().map(|values| {132            let preparation_command = if values.len() == 1 {133                &values[0]134            } else {135                &values[self.number]136            };137            Command::new_parametrized(138                None,139                preparation_command,140                self.command.get_parameters().iter().cloned(),141            )142        });143        let run_preparation_command = || {144            preparation_command145                .as_ref()146                .map(|cmd| self.run_preparation_command(cmd))147                .transpose()148        };149150        self.run_setup_command(self.command.get_parameters().iter().cloned())?;151152        // Warmup phase153        if self.options.warmup_count > 0 {154            let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {155                Some(get_progress_bar(156                    self.options.warmup_count,157                    "Performing warmup runs",158                    self.options.output_style,159                ))160            } else {161                None162            };163164            for _ in 0..self.options.warmup_count {165                let _ = run_preparation_command()?;166                let _ = self.executor.run_command_and_measure(self.command, None)?;167                if let Some(bar) = progress_bar.as_ref() {168                    bar.inc(1)169                }170            }171            if let Some(bar) = progress_bar.as_ref() {172                bar.finish_and_clear()173            }174        }175176        // Set up progress bar (and spinner for initial measurement)177        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {178            Some(get_progress_bar(179                self.options.run_bounds.min,180                "Initial time measurement",181                self.options.output_style,182            ))183        } else {184            None185        };186187        let preparation_result = run_preparation_command()?;188        let preparation_overhead =189            preparation_result.map_or(0.0, |res| res.time_real + self.executor.time_overhead());190191        // Initial timing run192        let (res, status) = self.executor.run_command_and_measure(self.command, None)?;193        let success = status.success();194195        // Determine number of benchmark runs196        let runs_in_min_time = (self.options.min_benchmarking_time197            / (res.time_real + self.executor.time_overhead() + preparation_overhead))198            as u64;199200        let count = {201            let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);202203            self.options204                .run_bounds205                .max206                .as_ref()207                .map(|max| cmp::min(min, *max))208                .unwrap_or(min)209        };210211        let count_remaining = count - 1;212213        // Save the first result214        times_real.push(res.time_real);215        times_user.push(res.time_user);216        times_system.push(res.time_system);217        exit_codes.push(extract_exit_code(status));218219        all_succeeded = all_succeeded && success;220221        // Re-configure the progress bar222        if let Some(bar) = progress_bar.as_ref() {223            bar.set_length(count)224        }225        if let Some(bar) = progress_bar.as_ref() {226            bar.inc(1)227        }228229        // Gather statistics (perform the actual benchmark)230        for _ in 0..count_remaining {231            run_preparation_command()?;232233            let msg = {234                let mean = format_duration(mean(&times_real), self.options.time_unit);235                format!("Current estimate: {}", mean.to_string().green())236            };237238            if let Some(bar) = progress_bar.as_ref() {239                bar.set_message(msg.to_owned())240            }241242            let (res, status) = self.executor.run_command_and_measure(self.command, None)?;243            let success = status.success();244245            times_real.push(res.time_real);246            times_user.push(res.time_user);247            times_system.push(res.time_system);248            exit_codes.push(extract_exit_code(status));249250            all_succeeded = all_succeeded && success;251252            if let Some(bar) = progress_bar.as_ref() {253                bar.inc(1)254            }255        }256257        if let Some(bar) = progress_bar.as_ref() {258            bar.finish_and_clear()259        }260261        // Compute statistical quantities262        let t_num = times_real.len();263        let t_mean = mean(&times_real);264        let t_stddev = if times_real.len() > 1 {265            Some(standard_deviation(&times_real, Some(t_mean)))266        } else {267            None268        };269        let t_median = median(&times_real);270        let t_min = min(&times_real);271        let t_max = max(&times_real);272273        let user_mean = mean(&times_user);274        let system_mean = mean(&times_system);275276        // Formatting and console output277        let (mean_str, time_unit) = format_duration_unit(t_mean, self.options.time_unit);278        let min_str = format_duration(t_min, Some(time_unit));279        let max_str = format_duration(t_max, Some(time_unit));280        let num_str = format!("{} runs", t_num);281282        let user_str = format_duration(user_mean, Some(time_unit));283        let system_str = format_duration(system_mean, Some(time_unit));284285        if self.options.output_style != OutputStyleOption::Disabled {286            if times_real.len() == 1 {287                println!(288                    "  Time ({} ≡):        {:>8}  {:>8}     [User: {}, System: {}]",289                    "abs".green().bold(),290                    mean_str.green().bold(),291                    "        ".to_string(), // alignment292                    user_str.blue(),293                    system_str.blue()294                );295            } else {296                let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));297298                println!(299                    "  Time ({} ± {}):     {:>8} ± {:>8}    [User: {}, System: {}]",300                    "mean".green().bold(),301                    "σ".green(),302                    mean_str.green().bold(),303                    stddev_str.green(),304                    user_str.blue(),305                    system_str.blue()306                );307308                println!(309                    "  Range ({} … {}):   {:>8} … {:>8}    {}",310                    "min".cyan(),311                    "max".purple(),312                    min_str.cyan(),313                    max_str.purple(),314                    num_str.dimmed()315                );316            }317        }318319        // Warnings320        let mut warnings = vec![];321322        // Check execution time323        if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {324            warnings.push(Warnings::FastExecutionTime);325        }326327        // Check programm exit codes328        if !all_succeeded {329            warnings.push(Warnings::NonZeroExitCode);330        }331332        // Run outlier detection333        let scores = modified_zscores(&times_real);334        if scores[0] > OUTLIER_THRESHOLD {335            warnings.push(Warnings::SlowInitialRun(times_real[0]));336        } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {337            warnings.push(Warnings::OutliersDetected);338        }339340        if !warnings.is_empty() {341            eprintln!(" ");342343            for warning in &warnings {344                eprintln!("  {}: {}", "Warning".yellow(), warning);345            }346        }347348        if self.options.output_style != OutputStyleOption::Disabled {349            println!(" ");350        }351352        self.run_cleanup_command(self.command.get_parameters().iter().cloned())?;353354        Ok(BenchmarkResult {355            command: command_name,356            mean: t_mean,357            stddev: t_stddev,358            median: t_median,359            user: user_mean,360            system: system_mean,361            min: t_min,362            max: t_max,363            times: Some(times_real),364            exit_codes,365            parameters: self366                .command367                .get_parameters()368                .iter()369                .map(|(name, value)| (name.to_string(), value.to_string()))370                .collect(),371        })372    }373}