Skip to content
Myr

mod.rs

This file

Path

src/benchmark/mod.rs

475 lines · 15.8 KiB · Rust

Last changed by

Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9

History of this file

Take it

1pub mod benchmark_result;2pub mod executor;3pub mod measurement;4pub mod scheduler;56use std::cmp;7use std::io::{self, Write};8use std::time::Instant;910use crate::benchmark::benchmark_result::Parameter;11use crate::benchmark::executor::BenchmarkIteration;12use crate::benchmark::measurement::{Measurement, Measurements};13use crate::command::Command;14use crate::options::{15    CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,16};17use crate::outlier_detection::OUTLIER_THRESHOLD;18use crate::output::console_writeln;19use crate::output::progress_bar::{20    finish_initial_measurement, get_progress_bar, set_benchmark_header, start_initial_measurement,21};22use crate::output::report;23use crate::output::warnings::{OutlierWarningOptions, Warnings};24use crate::parameter::ParameterNameAndValue;25use crate::quantity::{self, const_time_from_seconds, Time, Zero};26use benchmark_result::BenchmarkResult;2728use anyhow::{anyhow, ensure, Result};29use colored::*;3031use self::executor::Executor;3233/// Threshold for warning about fast execution time34pub const MIN_EXECUTION_TIME: Time = const_time_from_seconds(0.005);3536pub struct Benchmark<'a> {37    number: usize,38    command: &'a Command<'a>,39    options: &'a Options,40    executor: &'a dyn Executor,41}4243impl<'a> Benchmark<'a> {44    pub fn new(45        number: usize,46        command: &'a Command<'a>,47        options: &'a Options,48        executor: &'a dyn Executor,49    ) -> Self {50        Benchmark {51            number,52            command,53            options,54            executor,55        }56    }5758    /// Run setup, cleanup, or preparation commands59    fn run_intermediate_command(60        &self,61        command: &Command<'_>,62        error_output: &'static str,63        output_policy: &CommandOutputPolicy,64        iteration: executor::BenchmarkIteration,65    ) -> Result<Measurement> {66        self.executor67            .run_command_and_measure(68                command,69                iteration,70                Some(CmdFailureAction::RaiseError),71                output_policy,72            )73            .map_err(|_| anyhow!(error_output))74    }7576    /// Run the command specified by `--setup`.77    fn run_setup_command(78        &self,79        parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,80        output_policy: &CommandOutputPolicy,81    ) -> Result<Measurement> {82        let command = self83            .options84            .setup_command85            .as_ref()86            .map(|setup_command| Command::new_parametrized(None, setup_command, parameters));8788        let error_output = "The setup command terminated with a non-zero exit code. \89                            Append ' || true' to the command if you are sure that this can be ignored.";9091        Ok(command92            .map(|cmd| {93                self.run_intermediate_command(94                    &cmd,95                    error_output,96                    output_policy,97                    BenchmarkIteration::NonBenchmarkRun,98                )99            })100            .transpose()?101            .unwrap_or_default())102    }103104    /// Run the command specified by `--cleanup`.105    fn run_cleanup_command(106        &self,107        parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,108        output_policy: &CommandOutputPolicy,109    ) -> Result<Measurement> {110        let command = self111            .options112            .cleanup_command113            .as_ref()114            .map(|cleanup_command| Command::new_parametrized(None, cleanup_command, parameters));115116        let error_output = "The cleanup command terminated with a non-zero exit code. \117                            Append ' || true' to the command if you are sure that this can be ignored.";118119        Ok(command120            .map(|cmd| {121                self.run_intermediate_command(122                    &cmd,123                    error_output,124                    output_policy,125                    BenchmarkIteration::NonBenchmarkRun,126                )127            })128            .transpose()?129            .unwrap_or_default())130    }131132    /// Run the command specified by `--prepare`.133    fn run_preparation_command(134        &self,135        command: &Command<'_>,136        output_policy: &CommandOutputPolicy,137        iteration: executor::BenchmarkIteration,138    ) -> Result<Measurement> {139        let error_output = "The preparation command terminated with a non-zero exit code. \140                            Append ' || true' to the command if you are sure that this can be ignored.";141142        self.run_intermediate_command(command, error_output, output_policy, iteration)143    }144145    /// Run the command specified by `--conclude`.146    fn run_conclusion_command(147        &self,148        command: &Command<'_>,149        output_policy: &CommandOutputPolicy,150        iteration: executor::BenchmarkIteration,151    ) -> Result<Measurement> {152        let error_output = "The conclusion command terminated with a non-zero exit code. \153                            Append ' || true' to the command if you are sure that this can be ignored.";154155        self.run_intermediate_command(command, error_output, output_policy, iteration)156    }157158    fn validate_measurement(&self, measurement: &Measurement) -> Result<()> {159        if self.options.skip_unavailable_metrics {160            return Ok(());161        }162        for selection in &self.options.metrics {163            ensure!(selection.metric.value(measurement).is_some(),164                "Metric '{}' is unavailable for '{}'. Check platform support and hardware-counter permissions.",165                selection.metric.name(), self.command.get_command_line());166        }167        Ok(())168    }169170    /// Run the benchmark for a single command171    pub fn run(&self, reference: Option<&BenchmarkResult>) -> Result<BenchmarkResult> {172        let mut measurements = Measurements::default();173174        let output_policy = &self.options.command_output_policies[self.number];175176        let preparation_command = self.options.preparation_command.as_ref().map(|values| {177            let preparation_command = if values.len() == 1 {178                &values[0]179            } else {180                &values[self.number]181            };182            Command::new_parametrized(183                None,184                preparation_command,185                self.command.get_parameters().iter().cloned(),186            )187        });188189        let run_preparation_command = |iteration: executor::BenchmarkIteration| {190            preparation_command191                .as_ref()192                .map(|cmd| self.run_preparation_command(cmd, output_policy, iteration))193                .transpose()194        };195196        let conclusion_command = self.options.conclusion_command.as_ref().map(|values| {197            let conclusion_command = if values.len() == 1 {198                &values[0]199            } else {200                &values[self.number]201            };202            Command::new_parametrized(203                None,204                conclusion_command,205                self.command.get_parameters().iter().cloned(),206            )207        });208        let run_conclusion_command = |iteration: executor::BenchmarkIteration| {209            conclusion_command210                .as_ref()211                .map(|cmd| self.run_conclusion_command(cmd, output_policy, iteration))212                .transpose()213        };214215        self.run_setup_command(self.command.get_parameters().iter().cloned(), output_policy)?;216217        let progress_header = format!(218            "{}: {}",219            format!("Benchmark {}", self.number + 1).bold(),220            self.command221                .get_name_with_unused_parameters()222                .white()223                .bold()224        );225226        // Warmup phase227        if self.options.warmup_count > 0 {228            let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {229                Some(get_progress_bar(230                    self.options.warmup_count,231                    "Performing warmup runs",232                    self.options.output_style,233                ))234            } else {235                None236            };237238            if let Some(bar) = &progress_bar {239                set_benchmark_header(bar, progress_header.clone());240            }241242            for i in 0..self.options.warmup_count {243                let warmup_iteration = BenchmarkIteration::Warmup(i);244                let _ = run_preparation_command(warmup_iteration)?;245                let _ = self.executor.run_command_and_measure(246                    self.command,247                    warmup_iteration,248                    None,249                    output_policy,250                )?;251                let _ = run_conclusion_command(warmup_iteration)?;252                if let Some(bar) = progress_bar.as_ref() {253                    bar.inc(1)254                }255            }256            if let Some(bar) = progress_bar.as_ref() {257                bar.finish_and_clear()258            }259        }260261        // Set up progress bar (and spinner for initial measurement)262        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {263            Some(get_progress_bar(264                self.options.run_bounds.min,265                if preparation_command.is_some() {266                    "Running preparation command"267                } else {268                    "Initial run"269                },270                self.options.output_style,271            ))272        } else {273            None274        };275276        if let Some(bar) = &progress_bar {277            set_benchmark_header(bar, progress_header);278        }279280        let benchmark_iteration = BenchmarkIteration::Benchmark(0);281        let preparation_result = run_preparation_command(benchmark_iteration)?;282        let preparation_overhead = preparation_result.map_or(Time::zero(), |res| {283            res.time_wall_clock + self.executor.time_overhead()284        });285286        // Initial timing run287        if let Some(bar) = progress_bar.as_ref() {288            start_initial_measurement(bar, Instant::now());289        }290        let measurement = self.executor.run_command_and_measure(291            self.command,292            benchmark_iteration,293            None,294            output_policy,295        )?;296        self.validate_measurement(&measurement)?;297        let mut all_succeeded = measurement.exit_status.success();298299        if let Some(bar) = progress_bar.as_ref() {300            let primary = self.options.metrics[0];301            let value = primary.metric.value(&measurement).unwrap();302            let estimate = primary.display_unit(value).format(value);303            finish_initial_measurement(bar, format!("Current estimate: {}", estimate.green()));304        }305306        let conclusion_result = run_conclusion_command(benchmark_iteration)?;307        let conclusion_overhead = conclusion_result.map_or(Time::zero(), |res| {308            res.time_wall_clock + self.executor.time_overhead()309        });310311        // Determine number of benchmark runs312        let runs_in_min_time = (self.options.min_benchmarking_time313            / (measurement.time_wall_clock314                + self.executor.time_overhead()315                + preparation_overhead316                + conclusion_overhead))317            .get::<quantity::ratio>() as u64;318319        let count = {320            let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);321322            self.options323                .run_bounds324                .max325                .as_ref()326                .map(|max| cmp::min(min, *max))327                .unwrap_or(min)328        };329330        let count_remaining = count - 1;331332        // Save the first result333        let primary = self.options.metrics[0];334        let mut primary_total = primary.metric.value(&measurement).unwrap();335        measurements.push(measurement);336337        // Re-configure the progress bar338        if let Some(bar) = progress_bar.as_ref() {339            bar.set_length(count);340            bar.inc(1);341        }342343        // Gather statistics (perform the actual benchmark)344        for i in 0..count_remaining {345            let benchmark_iteration = BenchmarkIteration::Benchmark(i + 1);346347            if let Some(bar) = progress_bar.as_ref() {348                let mean = primary_total / measurements.len() as f64;349                bar.set_message(format!(350                    "Current estimate: {}",351                    primary.display_unit(mean).format(mean).green()352                ));353            }354355            run_preparation_command(benchmark_iteration)?;356357            let measurement = self.executor.run_command_and_measure(358                self.command,359                benchmark_iteration,360                None,361                output_policy,362            )?;363            self.validate_measurement(&measurement)?;364            let success = measurement.exit_status.success();365            primary_total += primary.metric.value(&measurement).unwrap();366            measurements.push(measurement);367368            all_succeeded = all_succeeded && success;369370            if let Some(bar) = progress_bar.as_ref() {371                bar.inc(1)372            }373374            run_conclusion_command(benchmark_iteration)?;375        }376377        if let Some(bar) = progress_bar.as_ref() {378            bar.finish_and_clear()379        }380381        if self.options.output_style != OutputStyleOption::Disabled {382            report::print(383                self.number,384                &self.command.get_name_with_unused_parameters(),385                &measurements,386                &self.options.metrics,387                self.options.skip_unavailable_metrics,388                reference,389            )?;390        }391392        // Warnings393        let mut warnings = vec![];394395        // Check execution time396        if self397            .options398            .metrics399            .iter()400            .any(|m| m.metric == crate::metric::Metric::TimeWallClock)401            && matches!(self.options.executor_kind, ExecutorKind::Shell(_))402            && measurements403                .wall_clock_times()404                .any(|t| t < MIN_EXECUTION_TIME)405        {406            warnings.push(Warnings::FastExecutionTime);407        }408409        // Check program exit codes410        if !all_succeeded {411            warnings.push(Warnings::NonZeroExitCode);412        }413414        // Run outlier detection415        let scores = measurements.modified_zscores(primary.metric);416417        let outlier_warning_options = OutlierWarningOptions {418            warmup_in_use: self.options.warmup_count > 0,419            prepare_in_use: self420                .options421                .preparation_command422                .as_ref()423                .map(|v| v.len())424                .unwrap_or(0)425                > 0,426        };427428        if scores[0] > OUTLIER_THRESHOLD {429            warnings.push(Warnings::InitialRunOutlier(430                primary,431                primary.metric.value(&measurements.measurements[0]).unwrap(),432                outlier_warning_options,433            ));434        }435436        if !warnings.is_empty() {437            let mut stderr = io::stderr().lock();438            console_writeln!(stderr, " ")?;439440            for warning in &warnings {441                console_writeln!(stderr, "  {}: {}", "Warning".yellow(), warning)?;442            }443        }444445        if self.options.output_style != OutputStyleOption::Disabled {446            console_writeln!(io::stdout(), " ")?;447        }448449        self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;450451        let command = self.command.get_command_line();452        let name = self.command.get_name();453        let name = (name != command).then_some(name);454455        Ok(BenchmarkResult {456            command,457            name,458            display_name: self.command.get_name_with_unused_parameters(),459            measurements,460            parameters: self461                .command462                .get_parameters()463                .iter()464                .map(|(name, value)| {465                    (466                        name.to_string(),467                        Parameter {468                            value: value.to_string(),469                        },470                    )471                })472                .collect(),473        })474    }475}