Skip to content
Myr

mod.rs

This file

Path

src/benchmark/mod.rs

483 lines · 16.1 KiB · Rust

Last changed by

Merge pull request #969 from sharkdp/codex/result-measurementsDavid Peterbefore adoptione689520

History of this file

Take it

1pub mod benchmark_result;2pub mod executor;3pub mod measurement;4pub mod relative_speed;5pub mod scheduler;67use std::cmp;8use std::io::{self, Write};910use crate::benchmark::executor::BenchmarkIteration;11use crate::command::Command;12use crate::options::{13    CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,14};15use crate::outlier_detection::OUTLIER_THRESHOLD;16use crate::output::console_writeln;17use crate::output::progress_bar::get_progress_bar;18use crate::output::warnings::{OutlierWarningOptions, Warnings};19use crate::parameter::ParameterNameAndValue;20use crate::quantity::{const_time_from_seconds, ratio, FormatQuantity, Time, Zero};21use benchmark_result::{BenchmarkResult, Parameter};22use measurement::{Measurement, Measurements};2324use anyhow::{anyhow, Result};25use colored::*;2627use self::executor::Executor;2829/// Threshold for warning about fast execution time30pub const MIN_EXECUTION_TIME: Time = const_time_from_seconds(5e-3);3132pub struct Benchmark<'a> {33    number: usize,34    command: &'a Command<'a>,35    options: &'a Options,36    executor: &'a dyn Executor,37}3839impl<'a> Benchmark<'a> {40    pub fn new(41        number: usize,42        command: &'a Command<'a>,43        options: &'a Options,44        executor: &'a dyn Executor,45    ) -> Self {46        Benchmark {47            number,48            command,49            options,50            executor,51        }52    }5354    /// Run setup, cleanup, or preparation commands55    fn run_intermediate_command(56        &self,57        command: &Command<'_>,58        error_output: &'static str,59        output_policy: &CommandOutputPolicy,60        iteration: executor::BenchmarkIteration,61    ) -> Result<Measurement> {62        self.executor63            .run_command_and_measure(64                command,65                iteration,66                Some(CmdFailureAction::RaiseError),67                output_policy,68            )69            .map_err(|_| anyhow!(error_output))70    }7172    /// Run the command specified by `--setup`.73    fn run_setup_command(74        &self,75        parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,76        output_policy: &CommandOutputPolicy,77    ) -> Result<Measurement> {78        let command = self79            .options80            .setup_command81            .as_ref()82            .map(|setup_command| Command::new_parametrized(None, setup_command, parameters));8384        let error_output = "The setup command terminated with a non-zero exit code. \85                            Append ' || true' to the command if you are sure that this can be ignored.";8687        Ok(command88            .map(|cmd| {89                self.run_intermediate_command(90                    &cmd,91                    error_output,92                    output_policy,93                    BenchmarkIteration::NonBenchmarkRun,94                )95            })96            .transpose()?97            .unwrap_or_default())98    }99100    /// Run the command specified by `--cleanup`.101    fn run_cleanup_command(102        &self,103        parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,104        output_policy: &CommandOutputPolicy,105    ) -> Result<Measurement> {106        let command = self107            .options108            .cleanup_command109            .as_ref()110            .map(|cleanup_command| Command::new_parametrized(None, cleanup_command, parameters));111112        let error_output = "The cleanup command terminated with a non-zero exit code. \113                            Append ' || true' to the command if you are sure that this can be ignored.";114115        Ok(command116            .map(|cmd| {117                self.run_intermediate_command(118                    &cmd,119                    error_output,120                    output_policy,121                    BenchmarkIteration::NonBenchmarkRun,122                )123            })124            .transpose()?125            .unwrap_or_default())126    }127128    /// Run the command specified by `--prepare`.129    fn run_preparation_command(130        &self,131        command: &Command<'_>,132        output_policy: &CommandOutputPolicy,133        iteration: executor::BenchmarkIteration,134    ) -> Result<Measurement> {135        let error_output = "The preparation command terminated with a non-zero exit code. \136                            Append ' || true' to the command if you are sure that this can be ignored.";137138        self.run_intermediate_command(command, error_output, output_policy, iteration)139    }140141    /// Run the command specified by `--conclude`.142    fn run_conclusion_command(143        &self,144        command: &Command<'_>,145        output_policy: &CommandOutputPolicy,146        iteration: executor::BenchmarkIteration,147    ) -> Result<Measurement> {148        let error_output = "The conclusion command terminated with a non-zero exit code. \149                            Append ' || true' to the command if you are sure that this can be ignored.";150151        self.run_intermediate_command(command, error_output, output_policy, iteration)152    }153154    /// Run the benchmark for a single command155    pub fn run(&self) -> Result<BenchmarkResult> {156        if self.options.output_style != OutputStyleOption::Disabled {157            console_writeln!(158                io::stdout(),159                "{}{}: {}",160                "Benchmark ".bold(),161                (self.number + 1).to_string().bold(),162                self.command.get_name_with_unused_parameters(),163            )?;164        }165166        let mut measurements = Measurements::default();167        let mut all_succeeded = true;168169        let output_policy = &self.options.command_output_policies[self.number];170171        let preparation_command = self.options.preparation_command.as_ref().map(|values| {172            let preparation_command = if values.len() == 1 {173                &values[0]174            } else {175                &values[self.number]176            };177            Command::new_parametrized(178                None,179                preparation_command,180                self.command.get_parameters().iter().cloned(),181            )182        });183184        let run_preparation_command = |iteration: executor::BenchmarkIteration| {185            preparation_command186                .as_ref()187                .map(|cmd| self.run_preparation_command(cmd, output_policy, iteration))188                .transpose()189        };190191        let conclusion_command = self.options.conclusion_command.as_ref().map(|values| {192            let conclusion_command = if values.len() == 1 {193                &values[0]194            } else {195                &values[self.number]196            };197            Command::new_parametrized(198                None,199                conclusion_command,200                self.command.get_parameters().iter().cloned(),201            )202        });203        let run_conclusion_command = |iteration: executor::BenchmarkIteration| {204            conclusion_command205                .as_ref()206                .map(|cmd| self.run_conclusion_command(cmd, output_policy, iteration))207                .transpose()208        };209210        self.run_setup_command(self.command.get_parameters().iter().cloned(), output_policy)?;211212        // Warmup phase213        if self.options.warmup_count > 0 {214            let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {215                Some(get_progress_bar(216                    self.options.warmup_count,217                    "Performing warmup runs",218                    self.options.output_style,219                ))220            } else {221                None222            };223224            for i in 0..self.options.warmup_count {225                let warmup_iteration = BenchmarkIteration::Warmup(i);226                let _ = run_preparation_command(warmup_iteration)?;227                let _ = self.executor.run_command_and_measure(228                    self.command,229                    warmup_iteration,230                    None,231                    output_policy,232                )?;233                let _ = run_conclusion_command(warmup_iteration)?;234                if let Some(bar) = progress_bar.as_ref() {235                    bar.inc(1)236                }237            }238            if let Some(bar) = progress_bar.as_ref() {239                bar.finish_and_clear()240            }241        }242243        // Set up progress bar (and spinner for initial measurement)244        let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {245            Some(get_progress_bar(246                self.options.run_bounds.min,247                "Initial time measurement",248                self.options.output_style,249            ))250        } else {251            None252        };253254        let benchmark_iteration = BenchmarkIteration::Benchmark(0);255        let preparation_result = run_preparation_command(benchmark_iteration)?;256        let preparation_overhead = preparation_result.map_or(Time::zero(), |res| {257            res.time_wall_clock + self.executor.time_overhead()258        });259260        // Initial timing run261        let res = self.executor.run_command_and_measure(262            self.command,263            benchmark_iteration,264            None,265            output_policy,266        )?;267        let success = res.exit_status.success();268269        let conclusion_result = run_conclusion_command(benchmark_iteration)?;270        let conclusion_overhead = conclusion_result.map_or(Time::zero(), |res| {271            res.time_wall_clock + self.executor.time_overhead()272        });273274        // Determine number of benchmark runs275        let runs_in_min_time = (self.options.min_benchmarking_time276            / (res.time_wall_clock277                + self.executor.time_overhead()278                + preparation_overhead279                + conclusion_overhead))280            .get::<ratio>() as u64;281282        let count = {283            let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);284285            self.options286                .run_bounds287                .max288                .as_ref()289                .map(|max| cmp::min(min, *max))290                .unwrap_or(min)291        };292293        let count_remaining = count - 1;294295        // Save the first result296        measurements.push(res);297298        all_succeeded = all_succeeded && success;299300        // Re-configure the progress bar301        if let Some(bar) = progress_bar.as_ref() {302            bar.set_length(count)303        }304        if let Some(bar) = progress_bar.as_ref() {305            bar.inc(1)306        }307308        // Gather statistics (perform the actual benchmark)309        for i in 0..count_remaining {310            let benchmark_iteration = BenchmarkIteration::Benchmark(i + 1);311            run_preparation_command(benchmark_iteration)?;312313            let msg = {314                let t_wall_clock_mean = measurements.time_wall_clock_mean();315                let time_unit = self316                    .options317                    .time_unit318                    .unwrap_or(t_wall_clock_mean.suitable_unit());319                let mean = t_wall_clock_mean.format(time_unit);320                format!("Current estimate: {}", mean.to_string().green())321            };322323            if let Some(bar) = progress_bar.as_ref() {324                bar.set_message(msg.to_owned())325            }326327            let res = self.executor.run_command_and_measure(328                self.command,329                benchmark_iteration,330                None,331                output_policy,332            )?;333            let success = res.exit_status.success();334335            measurements.push(res);336337            all_succeeded = all_succeeded && success;338339            if let Some(bar) = progress_bar.as_ref() {340                bar.inc(1)341            }342343            run_conclusion_command(benchmark_iteration)?;344        }345346        if let Some(bar) = progress_bar.as_ref() {347            bar.finish_and_clear()348        }349350        // Compute statistical quantities351        let t_num = measurements.len();352        let t_mean = measurements.time_wall_clock_mean();353        let t_stddev = measurements.stddev();354        let t_min = measurements.min();355        let t_max = measurements.max();356357        let user_mean = measurements.time_user_mean();358        let system_mean = measurements.time_system_mean();359360        // Formatting and console output361        let time_unit = self.options.time_unit.unwrap_or(t_mean.suitable_unit());362        let mean_str = t_mean.format(time_unit);363        let min_str = t_min.format(time_unit);364        let max_str = t_max.format(time_unit);365        let num_str = format!("{t_num} runs");366367        let user_str = user_mean.format(time_unit);368        let system_str = system_mean.format(time_unit);369370        if self.options.output_style != OutputStyleOption::Disabled {371            let mut stdout = io::stdout().lock();372            if measurements.len() == 1 {373                console_writeln!(374                    stdout,375                    "  Time ({} ≡):        {:>8}  {:>8}     [User: {}, System: {}]",376                    "abs".green().bold(),377                    mean_str.green().bold(),378                    "        ", // alignment379                    user_str.blue(),380                    system_str.blue()381                )?;382            } else {383                let stddev_str = t_stddev.unwrap().format(time_unit);384385                console_writeln!(386                    stdout,387                    "  Time ({} ± {}):     {:>8} ± {:>8}    [User: {}, System: {}]",388                    "mean".green().bold(),389                    "σ".green(),390                    mean_str.green().bold(),391                    stddev_str.green(),392                    user_str.blue(),393                    system_str.blue()394                )?;395396                console_writeln!(397                    stdout,398                    "  Range ({} … {}):   {:>8} … {:>8}    {}",399                    "min".cyan(),400                    "max".purple(),401                    min_str.cyan(),402                    max_str.purple(),403                    num_str.dimmed()404                )?;405            }406        }407408        // Warnings409        let mut warnings = vec![];410411        // Check execution time412        if matches!(self.options.executor_kind, ExecutorKind::Shell(_))413            && measurements414                .wall_clock_times()415                .any(|t| t < MIN_EXECUTION_TIME)416        {417            warnings.push(Warnings::FastExecutionTime);418        }419420        // Check program exit codes421        if !all_succeeded {422            warnings.push(Warnings::NonZeroExitCode);423        }424425        // Run outlier detection426        let scores = measurements.modified_zscores();427428        let outlier_warning_options = OutlierWarningOptions {429            warmup_in_use: self.options.warmup_count > 0,430            prepare_in_use: self431                .options432                .preparation_command433                .as_ref()434                .map(|v| v.len())435                .unwrap_or(0)436                > 0,437        };438439        if scores[0] > OUTLIER_THRESHOLD {440            warnings.push(Warnings::SlowInitialRun(441                measurements.wall_clock_times().next().unwrap(),442                outlier_warning_options,443            ));444        } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {445            warnings.push(Warnings::OutliersDetected(outlier_warning_options));446        }447448        if !warnings.is_empty() {449            let mut stderr = io::stderr().lock();450            console_writeln!(stderr, " ")?;451452            for warning in &warnings {453                console_writeln!(stderr, "  {}: {}", "Warning".yellow(), warning)?;454            }455        }456457        if self.options.output_style != OutputStyleOption::Disabled {458            console_writeln!(io::stdout(), " ")?;459        }460461        self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;462463        Ok(BenchmarkResult {464            command: self.command.get_name(),465            command_with_unused_parameters: self.command.get_name_with_unused_parameters(),466            measurements,467            parameters: self468                .command469                .get_parameters()470                .iter()471                .map(|(name, value)| {472                    (473                        name.to_string(),474                        Parameter {475                            value: value.to_string(),476                            is_unused: self.command.is_parameter_unused(name),477                        },478                    )479                })480                .collect(),481        })482    }483}