mod.rs
This file
Path
src/benchmark/mod.rs
469 lines · 15.5 KiB · Rust
Last changed by
Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02
History of this fileTake 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::{CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption};15use crate::outlier_detection::OUTLIER_THRESHOLD;16use crate::output::console_writeln;17use crate::output::progress_bar::{18 finish_initial_measurement, get_progress_bar, set_benchmark_header, start_initial_measurement,19};20use crate::output::report;21use crate::output::warnings::{OutlierWarningOptions, Warnings};22use crate::parameter::ParameterNameAndValue;23use crate::quantity::{self, const_time_from_seconds, Time, Zero};24use benchmark_result::BenchmarkResult;2526use anyhow::{anyhow, ensure, Result};27use colored::*;2829use self::executor::Executor;3031/// Threshold for warning about fast execution time32pub const MIN_EXECUTION_TIME: Time = const_time_from_seconds(0.005);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, preparation, or conclusion commands57 fn run_intermediate_command(58 &self,59 command: &Command<'_>,60 kind: &'static str,61 output_policy: &CommandOutputPolicy,62 iteration: executor::BenchmarkIteration,63 ) -> Result<Measurement> {64 let command = command.clone().with_environment_from(self.command);65 self.executor66 .run_intermediate_command_and_measure(&command, iteration, output_policy)67 .map_err(|error| {68 let hint = if cfg!(windows) {69 "Append ' || exit /b 0' to the command if this failure can be ignored."70 } else {71 "Append ' || true' to the command if this failure can be ignored."72 };73 anyhow!("The {kind} command failed: {error:#} {hint}")74 })75 }7677 /// Run the command specified by `--setup`.78 fn run_setup_command(79 &self,80 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,81 output_policy: &CommandOutputPolicy,82 ) -> Result<Measurement> {83 let command = self84 .options85 .setup_command86 .as_ref()87 .map(|setup_command| Command::new_parametrized(None, setup_command, parameters));8889 Ok(command90 .map(|cmd| {91 self.run_intermediate_command(92 &cmd,93 "setup",94 output_policy,95 BenchmarkIteration::NonBenchmarkRun,96 )97 })98 .transpose()?99 .unwrap_or_default())100 }101102 /// Run the command specified by `--cleanup`.103 fn run_cleanup_command(104 &self,105 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,106 output_policy: &CommandOutputPolicy,107 ) -> Result<Measurement> {108 let command = self109 .options110 .cleanup_command111 .as_ref()112 .map(|cleanup_command| Command::new_parametrized(None, cleanup_command, parameters));113114 Ok(command115 .map(|cmd| {116 self.run_intermediate_command(117 &cmd,118 "cleanup",119 output_policy,120 BenchmarkIteration::NonBenchmarkRun,121 )122 })123 .transpose()?124 .unwrap_or_default())125 }126127 /// Run the command specified by `--prepare`.128 fn run_preparation_command(129 &self,130 command: &Command<'_>,131 output_policy: &CommandOutputPolicy,132 iteration: executor::BenchmarkIteration,133 ) -> Result<Measurement> {134 self.run_intermediate_command(command, "preparation", output_policy, iteration)135 }136137 /// Run the command specified by `--conclude`.138 fn run_conclusion_command(139 &self,140 command: &Command<'_>,141 output_policy: &CommandOutputPolicy,142 iteration: executor::BenchmarkIteration,143 ) -> Result<Measurement> {144 self.run_intermediate_command(command, "conclusion", output_policy, iteration)145 }146147 fn validate_measurement(&self, measurement: &Measurement) -> Result<()> {148 if self.options.skip_unavailable_metrics {149 return Ok(());150 }151 for selection in &self.options.metrics {152 ensure!(selection.metric.value(measurement).is_some(),153 "Metric '{}' is unavailable for '{}'. Check platform support and hardware-counter permissions.",154 selection.metric.name(), self.command.get_command_line());155 }156 Ok(())157 }158159 /// Run the benchmark for a single command160 pub fn run(&self, reference: Option<&BenchmarkResult>) -> Result<BenchmarkResult> {161 let mut measurements = Measurements::default();162163 let output_policy = &self.options.command_output_policies[self.number];164165 let preparation_command = self.options.preparation_command.as_ref().map(|values| {166 let preparation_command = if values.len() == 1 {167 &values[0]168 } else {169 &values[self.number]170 };171 Command::new_parametrized(172 None,173 preparation_command,174 self.command.get_parameters().iter().cloned(),175 )176 });177178 let run_preparation_command = |iteration: executor::BenchmarkIteration| {179 preparation_command180 .as_ref()181 .map(|cmd| self.run_preparation_command(cmd, output_policy, iteration))182 .transpose()183 };184185 let conclusion_command = self.options.conclusion_command.as_ref().map(|values| {186 let conclusion_command = if values.len() == 1 {187 &values[0]188 } else {189 &values[self.number]190 };191 Command::new_parametrized(192 None,193 conclusion_command,194 self.command.get_parameters().iter().cloned(),195 )196 });197 let run_conclusion_command = |iteration: executor::BenchmarkIteration| {198 conclusion_command199 .as_ref()200 .map(|cmd| self.run_conclusion_command(cmd, output_policy, iteration))201 .transpose()202 };203204 self.run_setup_command(self.command.get_parameters().iter().cloned(), output_policy)?;205206 let progress_header = format!(207 "{}: {}",208 format!("Benchmark {}", self.number + 1).bold(),209 self.command210 .get_name_with_unused_parameters()211 .white()212 .bold()213 );214215 // Warmup phase216 if self.options.warmup_count > 0 {217 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {218 Some(get_progress_bar(219 self.options.warmup_count,220 "Performing warmup runs",221 self.options.output_style,222 ))223 } else {224 None225 };226227 if let Some(bar) = &progress_bar {228 set_benchmark_header(bar, progress_header.clone());229 }230231 for i in 0..self.options.warmup_count {232 let warmup_iteration = BenchmarkIteration::Warmup(i);233 let _ = run_preparation_command(warmup_iteration)?;234 let _ = self.executor.run_command_and_measure(235 self.command,236 warmup_iteration,237 None,238 output_policy,239 )?;240 let _ = run_conclusion_command(warmup_iteration)?;241 if let Some(bar) = progress_bar.as_ref() {242 bar.inc(1)243 }244 }245 if let Some(bar) = progress_bar.as_ref() {246 bar.finish_and_clear()247 }248 }249250 // Set up progress bar (and spinner for initial measurement)251 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {252 Some(get_progress_bar(253 self.options.run_bounds.min,254 if preparation_command.is_some() {255 "Running preparation command"256 } else {257 "Initial run"258 },259 self.options.output_style,260 ))261 } else {262 None263 };264265 if let Some(bar) = &progress_bar {266 set_benchmark_header(bar, progress_header);267 }268269 let benchmark_iteration = BenchmarkIteration::Benchmark(0);270 let preparation_result = run_preparation_command(benchmark_iteration)?;271 let preparation_overhead = preparation_result.map_or(Time::zero(), |res| {272 res.time_wall_clock + self.executor.time_overhead()273 });274275 // Initial timing run276 if let Some(bar) = progress_bar.as_ref() {277 start_initial_measurement(bar, Instant::now());278 }279 let measurement = self.executor.run_command_and_measure(280 self.command,281 benchmark_iteration,282 None,283 output_policy,284 )?;285 self.validate_measurement(&measurement)?;286 let mut all_succeeded = measurement.exit_status.success();287288 if let Some(bar) = progress_bar.as_ref() {289 let primary = self.options.metrics[0];290 let value = primary.metric.value(&measurement).unwrap();291 let estimate = primary.display_unit(value).format(value);292 finish_initial_measurement(bar, format!("Current estimate: {}", estimate.green()));293 }294295 let conclusion_result = run_conclusion_command(benchmark_iteration)?;296 let conclusion_overhead = conclusion_result.map_or(Time::zero(), |res| {297 res.time_wall_clock + self.executor.time_overhead()298 });299300 // Determine number of benchmark runs301 let runs_in_min_time = (self.options.min_benchmarking_time302 / (measurement.time_wall_clock303 + self.executor.time_overhead()304 + preparation_overhead305 + conclusion_overhead))306 .get::<quantity::ratio>() as u64;307308 let count = {309 let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);310311 self.options312 .run_bounds313 .max314 .as_ref()315 .map(|max| cmp::min(min, *max))316 .unwrap_or(min)317 };318319 let count_remaining = count - 1;320321 // Save the first result322 let primary = self.options.metrics[0];323 let mut primary_total = primary.metric.value(&measurement).unwrap();324 measurements.push(measurement);325326 // Re-configure the progress bar327 if let Some(bar) = progress_bar.as_ref() {328 bar.set_length(count);329 bar.inc(1);330 }331332 // Gather statistics (perform the actual benchmark)333 for i in 0..count_remaining {334 let benchmark_iteration = BenchmarkIteration::Benchmark(i + 1);335336 if let Some(bar) = progress_bar.as_ref() {337 let mean = primary_total / measurements.len() as f64;338 bar.set_message(format!(339 "Current estimate: {}",340 primary.display_unit(mean).format(mean).green()341 ));342 }343344 run_preparation_command(benchmark_iteration)?;345346 let measurement = self.executor.run_command_and_measure(347 self.command,348 benchmark_iteration,349 None,350 output_policy,351 )?;352 self.validate_measurement(&measurement)?;353 let success = measurement.exit_status.success();354 primary_total += primary.metric.value(&measurement).unwrap();355 measurements.push(measurement);356357 all_succeeded = all_succeeded && success;358359 if let Some(bar) = progress_bar.as_ref() {360 bar.inc(1)361 }362363 run_conclusion_command(benchmark_iteration)?;364 }365366 if let Some(bar) = progress_bar.as_ref() {367 bar.finish_and_clear()368 }369370 if self.options.output_style != OutputStyleOption::Disabled {371 report::print(372 self.number,373 &self.command.get_name_with_unused_parameters(),374 &measurements,375 &self.options.metrics,376 self.options.skip_unavailable_metrics,377 reference,378 )?;379 }380381 // Warnings382 let mut warnings = vec![];383384 // Check execution time385 if self386 .options387 .metrics388 .iter()389 .any(|m| m.metric == crate::metric::Metric::TimeWallClock)390 && matches!(self.options.executor_kind, ExecutorKind::Shell(_))391 && measurements392 .wall_clock_times()393 .any(|t| t < MIN_EXECUTION_TIME)394 {395 warnings.push(Warnings::FastExecutionTime);396 }397398 // Check program exit codes399 if !all_succeeded {400 warnings.push(Warnings::NonZeroExitCode);401 }402403 // Run outlier detection404 let scores = measurements.modified_zscores(primary.metric);405406 let outlier_warning_options = OutlierWarningOptions {407 warmup_in_use: self.options.warmup_count > 0,408 prepare_in_use: self409 .options410 .preparation_command411 .as_ref()412 .map(|v| v.len())413 .unwrap_or(0)414 > 0,415 };416417 if scores[0] > OUTLIER_THRESHOLD {418 warnings.push(Warnings::InitialRunOutlier(419 primary,420 primary.metric.value(&measurements.measurements[0]).unwrap(),421 outlier_warning_options,422 ));423 }424425 if !warnings.is_empty() {426 let mut stderr = io::stderr().lock();427 console_writeln!(stderr, " ")?;428429 for warning in &warnings {430 console_writeln!(stderr, " {}: {}", "Warning".yellow(), warning)?;431 }432 }433434 if self.options.output_style != OutputStyleOption::Disabled {435 console_writeln!(io::stdout(), " ")?;436 }437438 self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;439440 let command = self.command.get_command_line();441 let name = self.command.get_name();442 let name = (name != command).then_some(name);443444 Ok(BenchmarkResult {445 command,446 name,447 environment: self448 .command449 .get_environment()450 .map(|(name, value)| (name.to_owned(), value))451 .collect(),452 display_name: self.command.get_name_with_unused_parameters(),453 measurements,454 parameters: self455 .command456 .get_parameters()457 .iter()458 .map(|(name, value)| {459 (460 name.to_string(),461 Parameter {462 value: value.to_string(),463 },464 )465 })466 .collect(),467 })468 }469}