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
Provenance
- Commit
5c9c8c2- Tree
53f5863- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
d3c7c79
2 files changed+521 added−497 removed
modified:src/benchmark/mod.rs+514 added
1 unmodified line2 pub mod relative_speed;3 pub mod scheduler;4 pub mod timing_result;5 6+use std::cmp;7+use std::process::{ExitStatus, Stdio};8+9+use crate::command::Command;10+use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};11+use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};12+use crate::output::format::{format_duration, format_duration_unit};13+use crate::output::progress_bar::get_progress_bar;14+use crate::output::warnings::Warnings;15+use crate::parameter::ParameterNameAndValue;16+use crate::shell::execute_and_time;17+use crate::timer::wallclocktimer::WallClockTimer;18+use crate::timer::{TimerStart, TimerStop};19+use crate::util::exit_code::extract_exit_code;20+use crate::util::min_max::{max, min};21 use crate::util::units::Second;22+use benchmark_result::BenchmarkResult;23+use timing_result::TimingResult;24 25+use anyhow::{anyhow, bail, Result};26+use colored::*;27+use statistical::{mean, median, standard_deviation};28+29 /// Threshold for warning about fast execution time30 pub const MIN_EXECUTION_TIME: Second = 5e-3;31+32+/////////////// TODO: refactor the following part33+34+/// Correct for shell spawning time35+fn 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+}42+43+/// Run the given shell command and measure the execution time44+pub 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+ };55+56+ 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();59+60+ let mut time_user = result.user_time;61+ let mut time_system = result.system_time;62+63+ 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+ }73+74+ // 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+ }80+81+ Ok((82+ TimingResult {83+ time_real,84+ time_user,85+ time_system,86+ },87+ result.status,88+ ))89+}90+91+/// Measure the average shell spawning time92+pub 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+ };107+108+ let mut times_real: Vec<Second> = vec![];109+ let mut times_user: Vec<Second> = vec![];110+ let mut times_system: Vec<Second> = vec![];111+112+ 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+ );121+122+ match res {123+ Err(_) => {124+ let shell_cmd = if cfg!(windows) {125+ format!("{} /C \"\"", shell)126+ } else {127+ format!("{} -c \"\"", shell)128+ };129+130+ 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+ }141+142+ if let Some(bar) = progress_bar.as_ref() {143+ bar.inc(1)144+ }145+ }146+147+ if let Some(bar) = progress_bar.as_ref() {148+ bar.finish_and_clear()149+ }150+151+ Ok(TimingResult {152+ time_real: mean(×_real),153+ time_user: mean(×_user),154+ time_system: mean(×_system),155+ })156+}157+///////////////158+159+pub struct Benchmark<'a> {160+ number: usize,161+ command: &'a Command<'a>,162+ options: &'a Options,163+ shell_spawning_time: &'a TimingResult,164+}165+166+impl<'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+ }180+181+ /// 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+ }197+198+ /// 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));208+209+ 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.";211+212+ Ok(command213+ .map(|cmd| self.run_intermediate_command(&cmd, error_output))214+ .transpose()?215+ .unwrap_or_default())216+ }217+218+ /// 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));228+229+ 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.";231+232+ Ok(command233+ .map(|cmd| self.run_intermediate_command(&cmd, error_output))234+ .transpose()?235+ .unwrap_or_default())236+ }237+238+ /// 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.";242+243+ self.run_intermediate_command(command, error_output)244+ }245+246+ /// 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+ }257+258+ 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;263+264+ 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+ };283+284+ self.run_setup_command(self.command.get_parameters().iter().cloned())?;285+286+ // 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+ };297+298+ 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+ }315+316+ // 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+ };326+327+ let preparation_result = run_preparation_command()?;328+329+ // 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();338+339+ // 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;343+344+ let count = {345+ let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);346+347+ self.options348+ .run_bounds349+ .max350+ .as_ref()351+ .map(|max| cmp::min(min, *max))352+ .unwrap_or(min)353+ };354+355+ let count_remaining = count - 1;356+357+ // 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));362+363+ all_succeeded = all_succeeded && success;364+365+ // 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+ }372+373+ // Gather statistics (perform the actual benchmark)374+ for _ in 0..count_remaining {375+ run_preparation_command()?;376+377+ let msg = {378+ let mean = format_duration(mean(×_real), self.options.time_unit);379+ format!("Current estimate: {}", mean.to_string().green())380+ };381+382+ if let Some(bar) = progress_bar.as_ref() {383+ bar.set_message(msg.to_owned())384+ }385+386+ 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();394+395+ 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));399+400+ all_succeeded = all_succeeded && success;401+402+ if let Some(bar) = progress_bar.as_ref() {403+ bar.inc(1)404+ }405+ }406+407+ if let Some(bar) = progress_bar.as_ref() {408+ bar.finish_and_clear()409+ }410+411+ // Compute statistical quantities412+ let t_num = times_real.len();413+ let t_mean = mean(×_real);414+ let t_stddev = if times_real.len() > 1 {415+ Some(standard_deviation(×_real, Some(t_mean)))416+ } else {417+ None418+ };419+ let t_median = median(×_real);420+ let t_min = min(×_real);421+ let t_max = max(×_real);422+423+ let user_mean = mean(×_user);424+ let system_mean = mean(×_system);425+426+ // 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);431+432+ let user_str = format_duration(user_mean, Some(time_unit));433+ let system_str = format_duration(system_mean, Some(time_unit));434+435+ 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));447+448+ 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+ );457+458+ 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+ }468+469+ // Warnings470+ let mut warnings = vec![];471+472+ // Check execution time473+ if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {474+ warnings.push(Warnings::FastExecutionTime);475+ }476+477+ // Check programm exit codes478+ if !all_succeeded {479+ warnings.push(Warnings::NonZeroExitCode);480+ }481+482+ // Run outlier detection483+ let scores = modified_zscores(×_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+ }489+490+ if !warnings.is_empty() {491+ eprintln!(" ");492+493+ for warning in &warnings {494+ eprintln!(" {}: {}", "Warning".yellow(), warning);495+ }496+ }497+498+ if self.options.output_style != OutputStyleOption::Disabled {499+ println!(" ");500+ }501+502+ self.run_cleanup_command(self.command.get_parameters().iter().cloned())?;503+504+ 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
1-use std::cmp;2-use std::process::{ExitStatus, Stdio};3-1 use colored::*;5-use statistical::{mean, median, standard_deviation};2 3 use super::benchmark_result::BenchmarkResult;8-use super::timing_result::TimingResult;9-use super::{relative_speed, MIN_EXECUTION_TIME};4+use super::{relative_speed, Benchmark};5 11-use crate::command::Command;6 use crate::command::Commands;7 use crate::export::ExportManager;14-use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};15-use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};16-use crate::output::format::{format_duration, format_duration_unit};17-use crate::output::progress_bar::get_progress_bar;18-use crate::output::warnings::Warnings;19-use crate::parameter::ParameterNameAndValue;20-use crate::shell::execute_and_time;21-use crate::timer::wallclocktimer::WallClockTimer;22-use crate::timer::{TimerStart, TimerStop};23-use crate::util::exit_code::extract_exit_code;24-use crate::util::min_max::{max, min};25-use crate::util::units::Second;8+use crate::options::{Options, OutputStyleOption};9 27-use anyhow::{anyhow, bail, Result};10+use anyhow::Result;11 29-/////////////// TODO: refactor the following part30-31-/// Correct for shell spawning time32-fn 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-}39-40-/// Run the given shell command and measure the execution time41-pub 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- };52-53- 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();56-57- let mut time_user = result.user_time;58- let mut time_system = result.system_time;59-60- 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- }70-71- // 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- }77-78- Ok((79- TimingResult {80- time_real,81- time_user,82- time_system,83- },84- result.status,85- ))86-}87-88-/// Measure the average shell spawning time89-pub 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- };104-105- let mut times_real: Vec<Second> = vec![];106- let mut times_user: Vec<Second> = vec![];107- let mut times_system: Vec<Second> = vec![];108-109- 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- );118-119- match res {120- Err(_) => {121- let shell_cmd = if cfg!(windows) {122- format!("{} /C \"\"", shell)123- } else {124- format!("{} -c \"\"", shell)125- };126-127- 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- }138-139- if let Some(bar) = progress_bar.as_ref() {140- bar.inc(1)141- }142- }143-144- if let Some(bar) = progress_bar.as_ref() {145- bar.finish_and_clear()146- }147-148- Ok(TimingResult {149- time_real: mean(×_real),150- time_user: mean(×_user),151- time_system: mean(×_system),152- })153-}154-///////////////155-12 pub struct Scheduler<'a> {13 commands: &'a Commands<'a>,14 options: &'a Options,15 export_manager: &'a ExportManager,14 unmodified lines30 }31 }32 33 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 )?;40 184- 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()?);44 45 // 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_manager43 unmodified lines91 "Note".bold().red()92 );93 }94 }238-239- /// 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- }255-256- /// 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));266-267- 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.";269-270- Ok(command271- .map(|cmd| self.run_intermediate_command(&cmd, error_output))272- .transpose()?273- .unwrap_or_default())274- }275-276- /// 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));286-287- 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.";289-290- Ok(command291- .map(|cmd| self.run_intermediate_command(&cmd, error_output))292- .transpose()?293- .unwrap_or_default())294- }295-296- /// 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.";300-301- self.run_intermediate_command(command, error_output)302- }303-304- /// 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- }320-321- 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;326-327- 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- };346-347- self.run_setup_command(command.get_parameters().iter().cloned())?;348-349- // 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- };360-361- 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- }378-379- // 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- };389-390- let preparation_result = run_preparation_command()?;391-392- // 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();401-402- // 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;406-407- let count = {408- let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);409-410- self.options411- .run_bounds412- .max413- .as_ref()414- .map(|max| cmp::min(min, *max))415- .unwrap_or(min)416- };417-418- let count_remaining = count - 1;419-420- // 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));425-426- all_succeeded = all_succeeded && success;427-428- // 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- }435-436- // Gather statistics (perform the actual benchmark)437- for _ in 0..count_remaining {438- run_preparation_command()?;439-440- let msg = {441- let mean = format_duration(mean(×_real), self.options.time_unit);442- format!("Current estimate: {}", mean.to_string().green())443- };444-445- if let Some(bar) = progress_bar.as_ref() {446- bar.set_message(msg.to_owned())447- }448-449- 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();457-458- 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));462-463- all_succeeded = all_succeeded && success;464-465- if let Some(bar) = progress_bar.as_ref() {466- bar.inc(1)467- }468- }469-470- if let Some(bar) = progress_bar.as_ref() {471- bar.finish_and_clear()472- }473-474- // Compute statistical quantities475- let t_num = times_real.len();476- let t_mean = mean(×_real);477- let t_stddev = if times_real.len() > 1 {478- Some(standard_deviation(×_real, Some(t_mean)))479- } else {480- None481- };482- let t_median = median(×_real);483- let t_min = min(×_real);484- let t_max = max(×_real);485-486- let user_mean = mean(×_user);487- let system_mean = mean(×_system);488-489- // 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);494-495- let user_str = format_duration(user_mean, Some(time_unit));496- let system_str = format_duration(system_mean, Some(time_unit));497-498- 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));510-511- 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- );520-521- 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- }531-532- // Warnings533- let mut warnings = vec![];534-535- // Check execution time536- if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {537- warnings.push(Warnings::FastExecutionTime);538- }539-540- // Check programm exit codes541- if !all_succeeded {542- warnings.push(Warnings::NonZeroExitCode);543- }544-545- // Run outlier detection546- let scores = modified_zscores(×_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- }552-553- if !warnings.is_empty() {554- eprintln!(" ");555-556- for warning in &warnings {557- eprintln!(" {}: {}", "Warning".yellow(), warning);558- }559- }560-561- if self.options.output_style != OutputStyleOption::Disabled {562- println!(" ");563- }564-565- self.run_cleanup_command(command.get_parameters().iter().cloned())?;566-567- 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 }