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 fileTake it
The walk stopped after 200 commits: lines older than 6c0ec31 point at it.
Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 1–8why, one step back1pub mod benchmark_result;2pub mod executor;3pub mod relative_speed;4pub mod scheduler;5pub mod timing_result;67use std::cmp;8Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 9why, one step back9use crate::benchmark::executor::BenchmarkIteration;Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
line 10why, one step back10use crate::command::Command;Multiple output policiesDavid Peterbefore adoption99d24b7
lines 11–13why, one step back11use crate::options::{12 CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,13};Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 14–16why, one step back14use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};15use crate::output::format::{format_duration, format_duration_unit};16use crate::output::progress_bar::get_progress_bar;Improve hints for outlier warningsDavid Peterbefore adoption5b5daa0
line 17why, one step back17use crate::output::warnings::{OutlierWarningOptions, Warnings};Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 18–60why, one step back18use 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,Multiple output policiesDavid Peterbefore adoption99d24b7
line 61why, one step back61 output_policy: &CommandOutputPolicy,Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 62–63why, one step back62 ) -> Result<TimingResult> {63 self.executorAdd iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 64–67why, one step back64 .run_command_and_measure(65 command,66 executor::BenchmarkIteration::NonBenchmarkRun,67 Some(CmdFailureAction::RaiseError),Multiple output policiesDavid Peterbefore adoption99d24b7
line 68why, one step back68 output_policy,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 69why, one step back69 )Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 70–77why, one step back70 .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>>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 78why, one step back78 output_policy: &CommandOutputPolicy,Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 79–89why, one step back79 ) -> 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(commandMultiple output policiesDavid Peterbefore adoption99d24b7
line 90why, one step back90 .map(|cmd| self.run_intermediate_command(&cmd, error_output, output_policy))Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 91–98why, one step back91 .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>>,Multiple output policiesDavid Peterbefore adoption99d24b7
line 99why, one step back99 output_policy: &CommandOutputPolicy,Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 100–110why, one step back100 ) -> 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(commandMultiple output policiesDavid Peterbefore adoption99d24b7
line 111why, one step back111 .map(|cmd| self.run_intermediate_command(&cmd, error_output, output_policy))Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 112–116why, one step back112 .transpose()?113 .unwrap_or_default())114 }115116 /// Run the command specified by `--prepare`.Multiple output policiesDavid Peterbefore adoption99d24b7
lines 117–121why, one step back117 fn run_preparation_command(118 &self,119 command: &Command<'_>,120 output_policy: &CommandOutputPolicy,121 ) -> Result<TimingResult> {Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 122–124why, one step back122 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.";124Multiple output policiesDavid Peterbefore adoption99d24b7
line 125why, one step back125 self.run_intermediate_command(command, error_output, output_policy)Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 126–127why, one step back126 }127Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
line 128why, one step back128 /// Run the command specified by `--conclude`.Multiple output policiesDavid Peterbefore adoption99d24b7
lines 129–133why, one step back129 fn run_conclusion_command(130 &self,131 command: &Command<'_>,132 output_policy: &CommandOutputPolicy,133 ) -> Result<TimingResult> {Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
lines 134–136why, one step back134 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.";136Multiple output policiesDavid Peterbefore adoption99d24b7
line 137why, one step back137 self.run_intermediate_command(command, error_output, output_policy)Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
lines 138–139why, one step back138 }139Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 140–146why, one step back140 /// 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(),Show unused parameters in command namesDavid Peterbefore adoptiona875276
line 147why, one step back147 self.command.get_name_with_unused_parameters(),Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 148–153why, one step back148 );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![];Initial work on tracking memory usageDavid Peterbefore adoption6556b2b
line 154why, one step back154 let mut memory_usage_byte: Vec<u64> = vec![];Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 155–157why, one step back155 let mut exit_codes: Vec<Option<i32>> = vec![];156 let mut all_succeeded = true;157Multiple output policiesDavid Peterbefore adoption99d24b7
lines 158–159why, one step back158 let output_policy = &self.options.command_output_policies[self.number];159Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 160–171why, one step back160 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 });Multiple output policiesDavid Peterbefore adoption99d24b7
line 172why, one step back172Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 173–175why, one step back173 let run_preparation_command = || {174 preparation_command175 .as_ref()Multiple output policiesDavid Peterbefore adoption99d24b7
line 176why, one step back176 .map(|cmd| self.run_preparation_command(cmd, output_policy))Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 177–179why, one step back177 .transpose()178 };179Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
lines 180–194why, one step back180 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()Multiple output policiesDavid Peterbefore adoption99d24b7
line 195why, one step back195 .map(|cmd| self.run_conclusion_command(cmd, output_policy))Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
lines 196–198why, one step back196 .transpose()197 };198Multiple output policiesDavid Peterbefore adoption99d24b7
line 199why, one step back199 self.run_setup_command(self.command.get_parameters().iter().cloned(), output_policy)?;Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 200–212why, one step back200201 // 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 };212Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 213why, one step back213 for i in 0..self.options.warmup_count {Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
line 214why, one step back214 let _ = run_preparation_command()?;Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 215–218why, one step back215 let _ = self.executor.run_command_and_measure(216 self.command,217 BenchmarkIteration::Warmup(i),218 None,Multiple output policiesDavid Peterbefore adoption99d24b7
line 219why, one step back219 output_policy,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 220why, one step back220 )?;Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
line 221why, one step back221 let _ = run_conclusion_command()?;Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 222–246why, one step back222 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 runAdd iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 247–250why, one step back247 let (res, status) = self.executor.run_command_and_measure(248 self.command,249 BenchmarkIteration::Benchmark(0),250 None,Multiple output policiesDavid Peterbefore adoption99d24b7
line 251why, one step back251 output_policy,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 252why, one step back252 )?;Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 253–254why, one step back253 let success = status.success();254Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
lines 255–258why, one step back255 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());258Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 259–260why, one step back259 // Determine number of benchmark runs260 let runs_in_min_time = (self.options.min_benchmarking_timeAdd --conclude option with testsJack O'Connorbefore adoptione13d0cb
lines 261–264why, one step back261 / (res.time_real262 + self.executor.time_overhead()263 + preparation_overhead264 + conclusion_overhead)) as u64;Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 265–282why, one step back265266 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);Initial work on tracking memory usageDavid Peterbefore adoption6556b2b
line 283why, one step back283 memory_usage_byte.push(res.memory_usage_byte);Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 284–296why, one step back284 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)Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 297why, one step back297 for i in 0..count_remaining {Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 298–308why, one step back298 run_preparation_command()?;299300 let msg = {301 let mean = format_duration(mean(×_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 }308Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
lines 309–312why, one step back309 let (res, status) = self.executor.run_command_and_measure(310 self.command,311 BenchmarkIteration::Benchmark(i + 1),312 None,Multiple output policiesDavid Peterbefore adoption99d24b7
line 313why, one step back313 output_policy,Add iteration information to failure error messageDavid Peterbefore adoption83f04cd
line 314why, one step back314 )?;Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 315–319why, one step back315 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);Initial work on tracking memory usageDavid Peterbefore adoption6556b2b
line 320why, one step back320 memory_usage_byte.push(res.memory_usage_byte);Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 321–327why, one step back321 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 }Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
lines 328–329why, one step back328329 run_conclusion_command()?;Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 330–354why, one step back330 }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(×_real);339 let t_stddev = if times_real.len() > 1 {340 Some(standard_deviation(×_real, Some(t_mean)))341 } else {342 None343 };344 let t_median = median(×_real);345 let t_min = min(×_real);346 let t_max = max(×_real);347348 let user_mean = mean(×_user);349 let system_mean = mean(×_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));style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 355why, one step back355 let num_str = format!("{t_num} runs");Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 356–403why, one step back356357 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 }403Spelling and grammar fixesVille Skyttäbefore adoption178bdaa
line 404why, one step back404 // Check program exit codesUpdate deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 405–410why, one step back405 if !all_succeeded {406 warnings.push(Warnings::NonZeroExitCode);407 }408409 // Run outlier detection410 let scores = modified_zscores(×_real);Improve hints for outlier warningsDavid Peterbefore adoption5b5daa0
lines 411–422why, one step back411412 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 };422Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
line 423why, one step back423 if scores[0] > OUTLIER_THRESHOLD {Improve hints for outlier warningsDavid Peterbefore adoption5b5daa0
lines 424–427why, one step back424 warnings.push(Warnings::SlowInitialRun(425 times_real[0],426 outlier_warning_options,427 ));Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
line 428why, one step back428 } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {Improve hints for outlier warningsDavid Peterbefore adoption5b5daa0
line 429why, one step back429 warnings.push(Warnings::OutliersDetected(outlier_warning_options));Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 430–443why, one step back430 }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 }443Multiple output policiesDavid Peterbefore adoption99d24b7
line 444why, one step back444 self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 445–446why, one step back445446 Ok(BenchmarkResult {Show unused parameters in command namesDavid Peterbefore adoptiona875276
lines 447–448why, one step back447 command: self.command.get_name(),448 command_with_unused_parameters: self.command.get_name_with_unused_parameters(),Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 449–456why, one step back449 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),Initial work on tracking memory usageDavid Peterbefore adoption6556b2b
line 457why, one step back457 memory_usage_byte: Some(memory_usage_byte),Update deb package version on READMENickolas A Peresbefore adoption6c0ec31
lines 458–467why, one step back458 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}