Skip to content
Myr

mod.rs

This file

Path

src/benchmark/mod.rs

467 lines · 15.4 KiB · Rust

Last changed by

Initial work on tracking memory usageDavid Peterbefore adoption6556b2b

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::benchmark::executor::BenchmarkIteration;10use crate::command::Command;11use crate::options::{12    CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,13};14use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};15use crate::output::format::{format_duration, format_duration_unit};16use crate::output::progress_bar::get_progress_bar;17use crate::output::warnings::{OutlierWarningOptions, Warnings};18use crate::parameter::ParameterNameAndValue;19use crate::util::exit_code::extract_exit_code;20use crate::util::min_max::{max, min};21use crate::util::units::Second;22use benchmark_result::BenchmarkResult;23use timing_result::TimingResult;2425use anyhow::{anyhow, Result};26use colored::*;27use statistical::{mean, median, standard_deviation};2829use self::executor::Executor;3031/// Threshold for warning about fast execution time32pub const MIN_EXECUTION_TIME: Second = 5e-3;3334pub struct Benchmark<'a> {35    number: usize,36    command: &'a Command<'a>,37    options: &'a Options,38    executor: &'a dyn Executor,39}4041impl<'a> Benchmark<'a> {42    pub fn new(43        number: usize,44        command: &'a Command<'a>,45        options: &'a Options,46        executor: &'a dyn Executor,47    ) -> Self {48        Benchmark {49            number,50            command,51            options,52            executor,53        }54    }5556    /// Run setup, cleanup, or preparation commands57    fn run_intermediate_command(58        &self,59        command: &Command<'_>,60        error_output: &'static str,61        output_policy: &CommandOutputPolicy,62    ) -> Result<TimingResult> {63        self.executor64            .run_command_and_measure(65                command,66                executor::BenchmarkIteration::NonBenchmarkRun,67                Some(CmdFailureAction::RaiseError),68                output_policy,69            )70            .map(|r| r.0)71            .map_err(|_| anyhow!(error_output))72    }7374    /// Run the command specified by `--setup`.75    fn run_setup_command(76        &self,77        parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,78        output_policy: &CommandOutputPolicy,79    ) -> Result<TimingResult> {80        let command = self81            .options82            .setup_command83            .as_ref()84            .map(|setup_command| Command::new_parametrized(None, setup_command, parameters));8586        let error_output = "The setup command terminated with a non-zero exit code. \87                            Append ' || true' to the command if you are sure that this can be ignored.";8889        Ok(command90            .map(|cmd| self.run_intermediate_command(&cmd, error_output, output_policy))91            .transpose()?92            .unwrap_or_default())93    }9495    /// Run the command specified by `--cleanup`.96    fn run_cleanup_command(97        &self,98        parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,99        output_policy: &CommandOutputPolicy,100    ) -> Result<TimingResult> {101        let command = self102            .options103            .cleanup_command104            .as_ref()105            .map(|cleanup_command| Command::new_parametrized(None, cleanup_command, parameters));106107        let error_output = "The cleanup command terminated with a non-zero exit code. \108                            Append ' || true' to the command if you are sure that this can be ignored.";109110        Ok(command111            .map(|cmd| self.run_intermediate_command(&cmd, error_output, output_policy))112            .transpose()?113            .unwrap_or_default())114    }115116    /// Run the command specified by `--prepare`.117    fn run_preparation_command(118        &self,119        command: &Command<'_>,120        output_policy: &CommandOutputPolicy,121    ) -> Result<TimingResult> {122        let error_output = "The preparation command terminated with a non-zero exit code. \123                            Append ' || true' to the command if you are sure that this can be ignored.";124125        self.run_intermediate_command(command, error_output, output_policy)126    }127128    /// Run the command specified by `--conclude`.129    fn run_conclusion_command(130        &self,131        command: &Command<'_>,132        output_policy: &CommandOutputPolicy,133    ) -> Result<TimingResult> {134        let error_output = "The conclusion command terminated with a non-zero exit code. \135                            Append ' || true' to the command if you are sure that this can be ignored.";136137        self.run_intermediate_command(command, error_output, output_policy)138    }139140    /// Run the benchmark for a single command141    pub fn run(&self) -> Result<BenchmarkResult> {142        if self.options.output_style != OutputStyleOption::Disabled {143            println!(144                "{}{}: {}",145                "Benchmark ".bold(),146                (self.number + 1).to_string().bold(),147                self.command.get_name_with_unused_parameters(),148            );149        }150151        let mut times_real: Vec<Second> = vec![];152        let mut times_user: Vec<Second> = vec![];153        let mut times_system: Vec<Second> = vec![];154        let mut memory_usage_byte: Vec<u64> = vec![];155        let mut exit_codes: Vec<Option<i32>> = vec![];156        let mut all_succeeded = true;157158        let output_policy = &self.options.command_output_policies[self.number];159160        let preparation_command = self.options.preparation_command.as_ref().map(|values| {161            let preparation_command = if values.len() == 1 {162                &values[0]163            } else {164                &values[self.number]165            };166            Command::new_parametrized(167                None,168                preparation_command,169                self.command.get_parameters().iter().cloned(),170            )171        });172173        let run_preparation_command = || {174            preparation_command175                .as_ref()176                .map(|cmd| self.run_preparation_command(cmd, output_policy))177                .transpose()178        };179180        let conclusion_command = self.options.conclusion_command.as_ref().map(|values| {181            let conclusion_command = if values.len() == 1 {182                &values[0]183            } else {184                &values[self.number]185            };186            Command::new_parametrized(187                None,188                conclusion_command,189                self.command.get_parameters().iter().cloned(),190            )191        });192        let run_conclusion_command = || {193            conclusion_command194                .as_ref()195                .map(|cmd| self.run_conclusion_command(cmd, output_policy))196                .transpose()197        };198199        self.run_setup_command(self.command.get_parameters().iter().cloned(), output_policy)?;200201        // Warmup phase202        if self.options.warmup_count > 0 {203            let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {204                Some(get_progress_bar(205                    self.options.warmup_count,206                    "Performing warmup runs",207                    self.options.output_style,208                ))209            } else {210                None211            };212213            for i in 0..self.options.warmup_count {214                let _ = run_preparation_command()?;215                let _ = self.executor.run_command_and_measure(216                    self.command,217                    BenchmarkIteration::Warmup(i),218                    None,219                    output_policy,220                )?;221                let _ = run_conclusion_command()?;222                if let Some(bar) = progress_bar.as_ref() {223                    bar.inc(1)224                }225            }226            if let Some(bar) = progress_bar.as_ref() {227                bar.finish_and_clear()228            }229        }230231        // Set up progress bar (and spinner for initial measurement)232        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {233            Some(get_progress_bar(234                self.options.run_bounds.min,235                "Initial time measurement",236                self.options.output_style,237            ))238        } else {239            None240        };241242        let preparation_result = run_preparation_command()?;243        let preparation_overhead =244            preparation_result.map_or(0.0, |res| res.time_real + self.executor.time_overhead());245246        // Initial timing run247        let (res, status) = self.executor.run_command_and_measure(248            self.command,249            BenchmarkIteration::Benchmark(0),250            None,251            output_policy,252        )?;253        let success = status.success();254255        let conclusion_result = run_conclusion_command()?;256        let conclusion_overhead =257            conclusion_result.map_or(0.0, |res| res.time_real + self.executor.time_overhead());258259        // Determine number of benchmark runs260        let runs_in_min_time = (self.options.min_benchmarking_time261            / (res.time_real262                + self.executor.time_overhead()263                + preparation_overhead264                + conclusion_overhead)) as u64;265266        let count = {267            let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);268269            self.options270                .run_bounds271                .max272                .as_ref()273                .map(|max| cmp::min(min, *max))274                .unwrap_or(min)275        };276277        let count_remaining = count - 1;278279        // Save the first result280        times_real.push(res.time_real);281        times_user.push(res.time_user);282        times_system.push(res.time_system);283        memory_usage_byte.push(res.memory_usage_byte);284        exit_codes.push(extract_exit_code(status));285286        all_succeeded = all_succeeded && success;287288        // Re-configure the progress bar289        if let Some(bar) = progress_bar.as_ref() {290            bar.set_length(count)291        }292        if let Some(bar) = progress_bar.as_ref() {293            bar.inc(1)294        }295296        // Gather statistics (perform the actual benchmark)297        for i in 0..count_remaining {298            run_preparation_command()?;299300            let msg = {301                let mean = format_duration(mean(&times_real), self.options.time_unit);302                format!("Current estimate: {}", mean.to_string().green())303            };304305            if let Some(bar) = progress_bar.as_ref() {306                bar.set_message(msg.to_owned())307            }308309            let (res, status) = self.executor.run_command_and_measure(310                self.command,311                BenchmarkIteration::Benchmark(i + 1),312                None,313                output_policy,314            )?;315            let success = status.success();316317            times_real.push(res.time_real);318            times_user.push(res.time_user);319            times_system.push(res.time_system);320            memory_usage_byte.push(res.memory_usage_byte);321            exit_codes.push(extract_exit_code(status));322323            all_succeeded = all_succeeded && success;324325            if let Some(bar) = progress_bar.as_ref() {326                bar.inc(1)327            }328329            run_conclusion_command()?;330        }331332        if let Some(bar) = progress_bar.as_ref() {333            bar.finish_and_clear()334        }335336        // Compute statistical quantities337        let t_num = times_real.len();338        let t_mean = mean(&times_real);339        let t_stddev = if times_real.len() > 1 {340            Some(standard_deviation(&times_real, Some(t_mean)))341        } else {342            None343        };344        let t_median = median(&times_real);345        let t_min = min(&times_real);346        let t_max = max(&times_real);347348        let user_mean = mean(&times_user);349        let system_mean = mean(&times_system);350351        // Formatting and console output352        let (mean_str, time_unit) = format_duration_unit(t_mean, self.options.time_unit);353        let min_str = format_duration(t_min, Some(time_unit));354        let max_str = format_duration(t_max, Some(time_unit));355        let num_str = format!("{t_num} runs");356357        let user_str = format_duration(user_mean, Some(time_unit));358        let system_str = format_duration(system_mean, Some(time_unit));359360        if self.options.output_style != OutputStyleOption::Disabled {361            if times_real.len() == 1 {362                println!(363                    "  Time ({} ≡):        {:>8}  {:>8}     [User: {}, System: {}]",364                    "abs".green().bold(),365                    mean_str.green().bold(),366                    "        ", // alignment367                    user_str.blue(),368                    system_str.blue()369                );370            } else {371                let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));372373                println!(374                    "  Time ({} ± {}):     {:>8} ± {:>8}    [User: {}, System: {}]",375                    "mean".green().bold(),376                    "σ".green(),377                    mean_str.green().bold(),378                    stddev_str.green(),379                    user_str.blue(),380                    system_str.blue()381                );382383                println!(384                    "  Range ({} … {}):   {:>8} … {:>8}    {}",385                    "min".cyan(),386                    "max".purple(),387                    min_str.cyan(),388                    max_str.purple(),389                    num_str.dimmed()390                );391            }392        }393394        // Warnings395        let mut warnings = vec![];396397        // Check execution time398        if matches!(self.options.executor_kind, ExecutorKind::Shell(_))399            && times_real.iter().any(|&t| t < MIN_EXECUTION_TIME)400        {401            warnings.push(Warnings::FastExecutionTime);402        }403404        // Check program exit codes405        if !all_succeeded {406            warnings.push(Warnings::NonZeroExitCode);407        }408409        // Run outlier detection410        let scores = modified_zscores(&times_real);411412        let outlier_warning_options = OutlierWarningOptions {413            warmup_in_use: self.options.warmup_count > 0,414            prepare_in_use: self415                .options416                .preparation_command417                .as_ref()418                .map(|v| v.len())419                .unwrap_or(0)420                > 0,421        };422423        if scores[0] > OUTLIER_THRESHOLD {424            warnings.push(Warnings::SlowInitialRun(425                times_real[0],426                outlier_warning_options,427            ));428        } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {429            warnings.push(Warnings::OutliersDetected(outlier_warning_options));430        }431432        if !warnings.is_empty() {433            eprintln!(" ");434435            for warning in &warnings {436                eprintln!("  {}: {}", "Warning".yellow(), warning);437            }438        }439440        if self.options.output_style != OutputStyleOption::Disabled {441            println!(" ");442        }443444        self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;445446        Ok(BenchmarkResult {447            command: self.command.get_name(),448            command_with_unused_parameters: self.command.get_name_with_unused_parameters(),449            mean: t_mean,450            stddev: t_stddev,451            median: t_median,452            user: user_mean,453            system: system_mean,454            min: t_min,455            max: t_max,456            times: Some(times_real),457            memory_usage_byte: Some(memory_usage_byte),458            exit_codes,459            parameters: self460                .command461                .get_parameters()462                .iter()463                .map(|(name, value)| (name.to_string(), value.to_string()))464                .collect(),465        })466    }467}