Skip to content
Myr

New Benchmark struct

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Peter · committed by David Peter · parent d3c7c79 · Browse files · 2 files+521 added−497 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+521 added−497 removed

  • other:+521 added−497 removed

2 files+521 added−497 removed

modified:src/benchmark/mod.rs+514 added
1 unmodified line
2pub mod relative_speed;3pub mod scheduler;4pub mod timing_result;56use std::cmp;7use std::process::{ExitStatus, Stdio};89use crate::command::Command;10use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};11use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};12use crate::output::format::{format_duration, format_duration_unit};13use crate::output::progress_bar::get_progress_bar;14use crate::output::warnings::Warnings;15use crate::parameter::ParameterNameAndValue;16use crate::shell::execute_and_time;17use crate::timer::wallclocktimer::WallClockTimer;18use crate::timer::{TimerStart, TimerStop};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, bail, Result};26use colored::*;27use statistical::{mean, median, standard_deviation};2829/// Threshold for warning about fast execution time30pub const MIN_EXECUTION_TIME: Second = 5e-3;3132/////////////// TODO: refactor the following part3334/// Correct for shell spawning time35fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {36 if time < shell_spawning_time {37 0.038 } else {39 time - shell_spawning_time40 }41}4243/// Run the given shell command and measure the execution time44pub fn time_shell_command(45 shell: &Shell,46 command: &Command<'_>,47 command_output_policy: CommandOutputPolicy,48 failure_action: CmdFailureAction,49 shell_spawning_time: Option<&TimingResult>,50) -> Result<(TimingResult, ExitStatus)> {51 let (stdout, stderr) = match command_output_policy {52 CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),53 CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),54 };5556 let wallclock_timer = WallClockTimer::start();57 let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;58 let mut time_real = wallclock_timer.stop();5960 let mut time_user = result.user_time;61 let mut time_system = result.system_time;6263 if failure_action == CmdFailureAction::RaiseError && !result.status.success() {64 bail!(65 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \66 Alternatively, use the '--show-output' option to debug what went wrong.",67 result.status.code().map_or(68 "The process has been terminated by a signal".into(),69 |c| format!("Command terminated with non-zero exit code: {}", c)70 )71 );72 }7374 // Correct for shell spawning time75 if let Some(spawning_time) = shell_spawning_time {76 time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);77 time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);78 time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);79 }8081 Ok((82 TimingResult {83 time_real,84 time_user,85 time_system,86 },87 result.status,88 ))89}9091/// Measure the average shell spawning time92pub fn mean_shell_spawning_time(93 shell: &Shell,94 style: OutputStyleOption,95 command_output_policy: CommandOutputPolicy,96) -> Result<TimingResult> {97 const COUNT: u64 = 50;98 let progress_bar = if style != OutputStyleOption::Disabled {99 Some(get_progress_bar(100 COUNT,101 "Measuring shell spawning time",102 style,103 ))104 } else {105 None106 };107108 let mut times_real: Vec<Second> = vec![];109 let mut times_user: Vec<Second> = vec![];110 let mut times_system: Vec<Second> = vec![];111112 for _ in 0..COUNT {113 // Just run the shell without any command114 let res = time_shell_command(115 shell,116 &Command::new(None, ""),117 command_output_policy,118 CmdFailureAction::RaiseError,119 None,120 );121122 match res {123 Err(_) => {124 let shell_cmd = if cfg!(windows) {125 format!("{} /C \"\"", shell)126 } else {127 format!("{} -c \"\"", shell)128 };129130 bail!(131 "Could not measure shell execution time. Make sure you can run '{}'.",132 shell_cmd133 );134 }135 Ok((r, _)) => {136 times_real.push(r.time_real);137 times_user.push(r.time_user);138 times_system.push(r.time_system);139 }140 }141142 if let Some(bar) = progress_bar.as_ref() {143 bar.inc(1)144 }145 }146147 if let Some(bar) = progress_bar.as_ref() {148 bar.finish_and_clear()149 }150151 Ok(TimingResult {152 time_real: mean(&times_real),153 time_user: mean(&times_user),154 time_system: mean(&times_system),155 })156}157///////////////158159pub struct Benchmark<'a> {160 number: usize,161 command: &'a Command<'a>,162 options: &'a Options,163 shell_spawning_time: &'a TimingResult,164}165166impl<'a> Benchmark<'a> {167 pub fn new(168 number: usize,169 command: &'a Command<'a>,170 options: &'a Options,171 shell_spawning_time: &'a TimingResult,172 ) -> Self {173 Benchmark {174 number,175 command,176 options,177 shell_spawning_time,178 }179 }180181 /// Run setup, cleanup, or preparation commands182 fn run_intermediate_command(183 &self,184 command: &Command<'_>,185 error_output: &'static str,186 ) -> Result<TimingResult> {187 time_shell_command(188 &self.options.shell,189 command,190 self.options.command_output_policy,191 CmdFailureAction::RaiseError,192 None,193 )194 .map(|r| r.0)195 .map_err(|_| anyhow!(error_output))196 }197198 /// Run the command specified by `--setup`.199 fn run_setup_command(200 &self,201 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,202 ) -> Result<TimingResult> {203 let command = self204 .options205 .setup_command206 .as_ref()207 .map(|setup_command| Command::new_parametrized(None, setup_command, parameters));208209 let error_output = "The setup command terminated with a non-zero exit code. \210 Append ' || true' to the command if you are sure that this can be ignored.";211212 Ok(command213 .map(|cmd| self.run_intermediate_command(&cmd, error_output))214 .transpose()?215 .unwrap_or_default())216 }217218 /// Run the command specified by `--cleanup`.219 fn run_cleanup_command(220 &self,221 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,222 ) -> Result<TimingResult> {223 let command = self224 .options225 .cleanup_command226 .as_ref()227 .map(|cleanup_command| Command::new_parametrized(None, cleanup_command, parameters));228229 let error_output = "The cleanup command terminated with a non-zero exit code. \230 Append ' || true' to the command if you are sure that this can be ignored.";231232 Ok(command233 .map(|cmd| self.run_intermediate_command(&cmd, error_output))234 .transpose()?235 .unwrap_or_default())236 }237238 /// Run the command specified by `--prepare`.239 fn run_preparation_command(&self, command: &Command<'_>) -> Result<TimingResult> {240 let error_output = "The preparation command terminated with a non-zero exit code. \241 Append ' || true' to the command if you are sure that this can be ignored.";242243 self.run_intermediate_command(command, error_output)244 }245246 /// Run the benchmark for a single command247 pub fn run(&self) -> Result<BenchmarkResult> {248 let command_name = self.command.get_name();249 if self.options.output_style != OutputStyleOption::Disabled {250 println!(251 "{}{}: {}",252 "Benchmark ".bold(),253 (self.number + 1).to_string().bold(),254 command_name,255 );256 }257258 let mut times_real: Vec<Second> = vec![];259 let mut times_user: Vec<Second> = vec![];260 let mut times_system: Vec<Second> = vec![];261 let mut exit_codes: Vec<Option<i32>> = vec![];262 let mut all_succeeded = true;263264 let preparation_command = self.options.preparation_command.as_ref().map(|values| {265 let preparation_command = if values.len() == 1 {266 &values[0]267 } else {268 &values[self.number]269 };270 Command::new_parametrized(271 None,272 preparation_command,273 self.command.get_parameters().iter().cloned(),274 )275 });276 let run_preparation_command = || {277 if let Some(ref cmd) = preparation_command {278 self.run_preparation_command(cmd)279 } else {280 Ok(TimingResult::default())281 }282 };283284 self.run_setup_command(self.command.get_parameters().iter().cloned())?;285286 // Warmup phase287 if self.options.warmup_count > 0 {288 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {289 Some(get_progress_bar(290 self.options.warmup_count,291 "Performing warmup runs",292 self.options.output_style,293 ))294 } else {295 None296 };297298 for _ in 0..self.options.warmup_count {299 let _ = run_preparation_command()?;300 let _ = time_shell_command(301 &self.options.shell,302 self.command,303 self.options.command_output_policy,304 self.options.command_failure_action,305 None,306 )?;307 if let Some(bar) = progress_bar.as_ref() {308 bar.inc(1)309 }310 }311 if let Some(bar) = progress_bar.as_ref() {312 bar.finish_and_clear()313 }314 }315316 // Set up progress bar (and spinner for initial measurement)317 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {318 Some(get_progress_bar(319 self.options.run_bounds.min,320 "Initial time measurement",321 self.options.output_style,322 ))323 } else {324 None325 };326327 let preparation_result = run_preparation_command()?;328329 // Initial timing run330 let (res, status) = time_shell_command(331 &self.options.shell,332 self.command,333 self.options.command_output_policy,334 self.options.command_failure_action,335 Some(&self.shell_spawning_time),336 )?;337 let success = status.success();338339 // Determine number of benchmark runs340 let runs_in_min_time = (self.options.min_benchmarking_time341 / (res.time_real + preparation_result.time_real + self.shell_spawning_time.time_real))342 as u64;343344 let count = {345 let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);346347 self.options348 .run_bounds349 .max350 .as_ref()351 .map(|max| cmp::min(min, *max))352 .unwrap_or(min)353 };354355 let count_remaining = count - 1;356357 // Save the first result358 times_real.push(res.time_real);359 times_user.push(res.time_user);360 times_system.push(res.time_system);361 exit_codes.push(extract_exit_code(status));362363 all_succeeded = all_succeeded && success;364365 // Re-configure the progress bar366 if let Some(bar) = progress_bar.as_ref() {367 bar.set_length(count)368 }369 if let Some(bar) = progress_bar.as_ref() {370 bar.inc(1)371 }372373 // Gather statistics (perform the actual benchmark)374 for _ in 0..count_remaining {375 run_preparation_command()?;376377 let msg = {378 let mean = format_duration(mean(&times_real), self.options.time_unit);379 format!("Current estimate: {}", mean.to_string().green())380 };381382 if let Some(bar) = progress_bar.as_ref() {383 bar.set_message(msg.to_owned())384 }385386 let (res, status) = time_shell_command(387 &self.options.shell,388 self.command,389 self.options.command_output_policy,390 self.options.command_failure_action,391 Some(self.shell_spawning_time),392 )?;393 let success = status.success();394395 times_real.push(res.time_real);396 times_user.push(res.time_user);397 times_system.push(res.time_system);398 exit_codes.push(extract_exit_code(status));399400 all_succeeded = all_succeeded && success;401402 if let Some(bar) = progress_bar.as_ref() {403 bar.inc(1)404 }405 }406407 if let Some(bar) = progress_bar.as_ref() {408 bar.finish_and_clear()409 }410411 // Compute statistical quantities412 let t_num = times_real.len();413 let t_mean = mean(&times_real);414 let t_stddev = if times_real.len() > 1 {415 Some(standard_deviation(&times_real, Some(t_mean)))416 } else {417 None418 };419 let t_median = median(&times_real);420 let t_min = min(&times_real);421 let t_max = max(&times_real);422423 let user_mean = mean(&times_user);424 let system_mean = mean(&times_system);425426 // Formatting and console output427 let (mean_str, time_unit) = format_duration_unit(t_mean, self.options.time_unit);428 let min_str = format_duration(t_min, Some(time_unit));429 let max_str = format_duration(t_max, Some(time_unit));430 let num_str = format!("{} runs", t_num);431432 let user_str = format_duration(user_mean, Some(time_unit));433 let system_str = format_duration(system_mean, Some(time_unit));434435 if self.options.output_style != OutputStyleOption::Disabled {436 if times_real.len() == 1 {437 println!(438 " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",439 "abs".green().bold(),440 mean_str.green().bold(),441 " ".to_string(), // alignment442 user_str.blue(),443 system_str.blue()444 );445 } else {446 let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));447448 println!(449 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",450 "mean".green().bold(),451 "σ".green(),452 mean_str.green().bold(),453 stddev_str.green(),454 user_str.blue(),455 system_str.blue()456 );457458 println!(459 " Range ({} … {}): {:>8} … {:>8} {}",460 "min".cyan(),461 "max".purple(),462 min_str.cyan(),463 max_str.purple(),464 num_str.dimmed()465 );466 }467 }468469 // Warnings470 let mut warnings = vec![];471472 // Check execution time473 if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {474 warnings.push(Warnings::FastExecutionTime);475 }476477 // Check programm exit codes478 if !all_succeeded {479 warnings.push(Warnings::NonZeroExitCode);480 }481482 // Run outlier detection483 let scores = modified_zscores(&times_real);484 if scores[0] > OUTLIER_THRESHOLD {485 warnings.push(Warnings::SlowInitialRun(times_real[0]));486 } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {487 warnings.push(Warnings::OutliersDetected);488 }489490 if !warnings.is_empty() {491 eprintln!(" ");492493 for warning in &warnings {494 eprintln!(" {}: {}", "Warning".yellow(), warning);495 }496 }497498 if self.options.output_style != OutputStyleOption::Disabled {499 println!(" ");500 }501502 self.run_cleanup_command(self.command.get_parameters().iter().cloned())?;503504 Ok(BenchmarkResult {505 command: command_name,506 mean: t_mean,507 stddev: t_stddev,508 median: t_median,509 user: user_mean,510 system: system_mean,511 min: t_min,512 max: t_max,513 times: Some(times_real),514 exit_codes,515 parameters: self516 .command517 .get_parameters()518 .iter()519 .map(|(name, value)| (name.to_string(), value.to_string()))520 .collect(),521 })522 }523}
modified:src/benchmark/scheduler.rs+7 added-497 removed
1use std::cmp;2use std::process::{ExitStatus, Stdio};31use colored::*;5use statistical::{mean, median, standard_deviation};23use super::benchmark_result::BenchmarkResult;8use super::timing_result::TimingResult;9use super::{relative_speed, MIN_EXECUTION_TIME};4use super::{relative_speed, Benchmark};511use crate::command::Command;6use crate::command::Commands;7use crate::export::ExportManager;14use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};15use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};16use crate::output::format::{format_duration, format_duration_unit};17use crate::output::progress_bar::get_progress_bar;18use crate::output::warnings::Warnings;19use crate::parameter::ParameterNameAndValue;20use crate::shell::execute_and_time;21use crate::timer::wallclocktimer::WallClockTimer;22use crate::timer::{TimerStart, TimerStop};23use crate::util::exit_code::extract_exit_code;24use crate::util::min_max::{max, min};25use crate::util::units::Second;8use crate::options::{Options, OutputStyleOption};927use anyhow::{anyhow, bail, Result};10use anyhow::Result;1129/////////////// TODO: refactor the following part3031/// Correct for shell spawning time32fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {33 if time < shell_spawning_time {34 0.035 } else {36 time - shell_spawning_time37 }38}3940/// Run the given shell command and measure the execution time41pub fn time_shell_command(42 shell: &Shell,43 command: &Command<'_>,44 command_output_policy: CommandOutputPolicy,45 failure_action: CmdFailureAction,46 shell_spawning_time: Option<TimingResult>,47) -> Result<(TimingResult, ExitStatus)> {48 let (stdout, stderr) = match command_output_policy {49 CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),50 CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),51 };5253 let wallclock_timer = WallClockTimer::start();54 let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;55 let mut time_real = wallclock_timer.stop();5657 let mut time_user = result.user_time;58 let mut time_system = result.system_time;5960 if failure_action == CmdFailureAction::RaiseError && !result.status.success() {61 bail!(62 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \63 Alternatively, use the '--show-output' option to debug what went wrong.",64 result.status.code().map_or(65 "The process has been terminated by a signal".into(),66 |c| format!("Command terminated with non-zero exit code: {}", c)67 )68 );69 }7071 // Correct for shell spawning time72 if let Some(spawning_time) = shell_spawning_time {73 time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);74 time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);75 time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);76 }7778 Ok((79 TimingResult {80 time_real,81 time_user,82 time_system,83 },84 result.status,85 ))86}8788/// Measure the average shell spawning time89pub fn mean_shell_spawning_time(90 shell: &Shell,91 style: OutputStyleOption,92 command_output_policy: CommandOutputPolicy,93) -> Result<TimingResult> {94 const COUNT: u64 = 50;95 let progress_bar = if style != OutputStyleOption::Disabled {96 Some(get_progress_bar(97 COUNT,98 "Measuring shell spawning time",99 style,100 ))101 } else {102 None103 };104105 let mut times_real: Vec<Second> = vec![];106 let mut times_user: Vec<Second> = vec![];107 let mut times_system: Vec<Second> = vec![];108109 for _ in 0..COUNT {110 // Just run the shell without any command111 let res = time_shell_command(112 shell,113 &Command::new(None, ""),114 command_output_policy,115 CmdFailureAction::RaiseError,116 None,117 );118119 match res {120 Err(_) => {121 let shell_cmd = if cfg!(windows) {122 format!("{} /C \"\"", shell)123 } else {124 format!("{} -c \"\"", shell)125 };126127 bail!(128 "Could not measure shell execution time. Make sure you can run '{}'.",129 shell_cmd130 );131 }132 Ok((r, _)) => {133 times_real.push(r.time_real);134 times_user.push(r.time_user);135 times_system.push(r.time_system);136 }137 }138139 if let Some(bar) = progress_bar.as_ref() {140 bar.inc(1)141 }142 }143144 if let Some(bar) = progress_bar.as_ref() {145 bar.finish_and_clear()146 }147148 Ok(TimingResult {149 time_real: mean(&times_real),150 time_user: mean(&times_user),151 time_system: mean(&times_system),152 })153}154///////////////15512pub struct Scheduler<'a> {13 commands: &'a Commands<'a>,14 options: &'a Options,15 export_manager: &'a ExportManager,
14 unmodified lines
30 }31 }3233 pub fn run_benchmarks(&mut self) -> Result<()> {178 let shell_spawning_time = mean_shell_spawning_time(34 let shell_spawning_time = super::mean_shell_spawning_time(35 // TODO36 &self.options.shell,37 self.options.output_style,38 self.options.command_output_policy,39 )?;40184 for (benchmark_number, cmd) in self.commands.iter().enumerate() {41 for (number, cmd) in self.commands.iter().enumerate() {42 self.results186 .push(self.run_benchmark(benchmark_number, cmd, shell_spawning_time)?);43 .push(Benchmark::new(number, cmd, self.options, &shell_spawning_time).run()?);4445 // We export (all results so far) after each individual benchmark, because46 // we would risk losing all results if a later benchmark fails.47 self.export_manager
43 unmodified lines
91 "Note".bold().red()92 );93 }94 }238239 /// Run setup, cleanup, or preparation commands240 fn run_intermediate_command(241 &self,242 command: &Command<'_>,243 error_output: &'static str,244 ) -> Result<TimingResult> {245 time_shell_command(246 &self.options.shell,247 command,248 self.options.command_output_policy,249 CmdFailureAction::RaiseError,250 None,251 )252 .map(|r| r.0)253 .map_err(|_| anyhow!(error_output))254 }255256 /// Run the command specified by `--setup`.257 fn run_setup_command(258 &self,259 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,260 ) -> Result<TimingResult> {261 let command = self262 .options263 .setup_command264 .as_ref()265 .map(|setup_command| Command::new_parametrized(None, setup_command, parameters));266267 let error_output = "The setup command terminated with a non-zero exit code. \268 Append ' || true' to the command if you are sure that this can be ignored.";269270 Ok(command271 .map(|cmd| self.run_intermediate_command(&cmd, error_output))272 .transpose()?273 .unwrap_or_default())274 }275276 /// Run the command specified by `--cleanup`.277 fn run_cleanup_command(278 &self,279 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,280 ) -> Result<TimingResult> {281 let command = self282 .options283 .cleanup_command284 .as_ref()285 .map(|cleanup_command| Command::new_parametrized(None, cleanup_command, parameters));286287 let error_output = "The cleanup command terminated with a non-zero exit code. \288 Append ' || true' to the command if you are sure that this can be ignored.";289290 Ok(command291 .map(|cmd| self.run_intermediate_command(&cmd, error_output))292 .transpose()?293 .unwrap_or_default())294 }295296 /// Run the command specified by `--prepare`.297 fn run_preparation_command(&self, command: &Command<'_>) -> Result<TimingResult> {298 let error_output = "The preparation command terminated with a non-zero exit code. \299 Append ' || true' to the command if you are sure that this can be ignored.";300301 self.run_intermediate_command(command, error_output)302 }303304 /// Run the benchmark for a single command305 pub fn run_benchmark(306 &self,307 benchmark_number: usize,308 command: &Command<'_>,309 shell_spawning_time: TimingResult,310 ) -> Result<BenchmarkResult> {311 let command_name = command.get_name();312 if self.options.output_style != OutputStyleOption::Disabled {313 println!(314 "{}{}: {}",315 "Benchmark ".bold(),316 (benchmark_number + 1).to_string().bold(),317 command_name,318 );319 }320321 let mut times_real: Vec<Second> = vec![];322 let mut times_user: Vec<Second> = vec![];323 let mut times_system: Vec<Second> = vec![];324 let mut exit_codes: Vec<Option<i32>> = vec![];325 let mut all_succeeded = true;326327 let preparation_command = self.options.preparation_command.as_ref().map(|values| {328 let preparation_command = if values.len() == 1 {329 &values[0]330 } else {331 &values[benchmark_number]332 };333 Command::new_parametrized(334 None,335 preparation_command,336 command.get_parameters().iter().cloned(),337 )338 });339 let run_preparation_command = || {340 if let Some(ref cmd) = preparation_command {341 self.run_preparation_command(cmd)342 } else {343 Ok(TimingResult::default())344 }345 };346347 self.run_setup_command(command.get_parameters().iter().cloned())?;348349 // Warmup phase350 if self.options.warmup_count > 0 {351 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {352 Some(get_progress_bar(353 self.options.warmup_count,354 "Performing warmup runs",355 self.options.output_style,356 ))357 } else {358 None359 };360361 for _ in 0..self.options.warmup_count {362 let _ = run_preparation_command()?;363 let _ = time_shell_command(364 &self.options.shell,365 command,366 self.options.command_output_policy,367 self.options.command_failure_action,368 None,369 )?;370 if let Some(bar) = progress_bar.as_ref() {371 bar.inc(1)372 }373 }374 if let Some(bar) = progress_bar.as_ref() {375 bar.finish_and_clear()376 }377 }378379 // Set up progress bar (and spinner for initial measurement)380 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {381 Some(get_progress_bar(382 self.options.run_bounds.min,383 "Initial time measurement",384 self.options.output_style,385 ))386 } else {387 None388 };389390 let preparation_result = run_preparation_command()?;391392 // Initial timing run393 let (res, status) = time_shell_command(394 &self.options.shell,395 command,396 self.options.command_output_policy,397 self.options.command_failure_action,398 Some(shell_spawning_time),399 )?;400 let success = status.success();401402 // Determine number of benchmark runs403 let runs_in_min_time = (self.options.min_benchmarking_time404 / (res.time_real + preparation_result.time_real + shell_spawning_time.time_real))405 as u64;406407 let count = {408 let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);409410 self.options411 .run_bounds412 .max413 .as_ref()414 .map(|max| cmp::min(min, *max))415 .unwrap_or(min)416 };417418 let count_remaining = count - 1;419420 // Save the first result421 times_real.push(res.time_real);422 times_user.push(res.time_user);423 times_system.push(res.time_system);424 exit_codes.push(extract_exit_code(status));425426 all_succeeded = all_succeeded && success;427428 // Re-configure the progress bar429 if let Some(bar) = progress_bar.as_ref() {430 bar.set_length(count)431 }432 if let Some(bar) = progress_bar.as_ref() {433 bar.inc(1)434 }435436 // Gather statistics (perform the actual benchmark)437 for _ in 0..count_remaining {438 run_preparation_command()?;439440 let msg = {441 let mean = format_duration(mean(&times_real), self.options.time_unit);442 format!("Current estimate: {}", mean.to_string().green())443 };444445 if let Some(bar) = progress_bar.as_ref() {446 bar.set_message(msg.to_owned())447 }448449 let (res, status) = time_shell_command(450 &self.options.shell,451 command,452 self.options.command_output_policy,453 self.options.command_failure_action,454 Some(shell_spawning_time),455 )?;456 let success = status.success();457458 times_real.push(res.time_real);459 times_user.push(res.time_user);460 times_system.push(res.time_system);461 exit_codes.push(extract_exit_code(status));462463 all_succeeded = all_succeeded && success;464465 if let Some(bar) = progress_bar.as_ref() {466 bar.inc(1)467 }468 }469470 if let Some(bar) = progress_bar.as_ref() {471 bar.finish_and_clear()472 }473474 // Compute statistical quantities475 let t_num = times_real.len();476 let t_mean = mean(&times_real);477 let t_stddev = if times_real.len() > 1 {478 Some(standard_deviation(&times_real, Some(t_mean)))479 } else {480 None481 };482 let t_median = median(&times_real);483 let t_min = min(&times_real);484 let t_max = max(&times_real);485486 let user_mean = mean(&times_user);487 let system_mean = mean(&times_system);488489 // Formatting and console output490 let (mean_str, time_unit) = format_duration_unit(t_mean, self.options.time_unit);491 let min_str = format_duration(t_min, Some(time_unit));492 let max_str = format_duration(t_max, Some(time_unit));493 let num_str = format!("{} runs", t_num);494495 let user_str = format_duration(user_mean, Some(time_unit));496 let system_str = format_duration(system_mean, Some(time_unit));497498 if self.options.output_style != OutputStyleOption::Disabled {499 if times_real.len() == 1 {500 println!(501 " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",502 "abs".green().bold(),503 mean_str.green().bold(),504 " ".to_string(), // alignment505 user_str.blue(),506 system_str.blue()507 );508 } else {509 let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));510511 println!(512 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",513 "mean".green().bold(),514 "σ".green(),515 mean_str.green().bold(),516 stddev_str.green(),517 user_str.blue(),518 system_str.blue()519 );520521 println!(522 " Range ({} … {}): {:>8} … {:>8} {}",523 "min".cyan(),524 "max".purple(),525 min_str.cyan(),526 max_str.purple(),527 num_str.dimmed()528 );529 }530 }531532 // Warnings533 let mut warnings = vec![];534535 // Check execution time536 if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {537 warnings.push(Warnings::FastExecutionTime);538 }539540 // Check programm exit codes541 if !all_succeeded {542 warnings.push(Warnings::NonZeroExitCode);543 }544545 // Run outlier detection546 let scores = modified_zscores(&times_real);547 if scores[0] > OUTLIER_THRESHOLD {548 warnings.push(Warnings::SlowInitialRun(times_real[0]));549 } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {550 warnings.push(Warnings::OutliersDetected);551 }552553 if !warnings.is_empty() {554 eprintln!(" ");555556 for warning in &warnings {557 eprintln!(" {}: {}", "Warning".yellow(), warning);558 }559 }560561 if self.options.output_style != OutputStyleOption::Disabled {562 println!(" ");563 }564565 self.run_cleanup_command(command.get_parameters().iter().cloned())?;566567 Ok(BenchmarkResult {568 command: command_name,569 mean: t_mean,570 stddev: t_stddev,571 median: t_median,572 user: user_mean,573 system: system_mean,574 min: t_min,575 max: t_max,576 times: Some(times_real),577 exit_codes,578 parameters: command579 .get_parameters()580 .iter()581 .map(|(name, value)| (name.to_string(), value.to_string()))582 .collect(),583 })584 }95}