Skip to content
Myr

Move functionality to scheduler

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 b658e20 · Browse files · 11 files+560 added−560 removed
This commit

State

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

Diff stats

11 files+560 added−560 removed

  • other:+560 added−560 removed

11 files+560 added−560 removed

added:src/benchmark/benchmark_result.rs+46 added
1use std::collections::BTreeMap;23use serde::Serialize;45use crate::util::units::Second;67/// Set of values that will be exported.8// NOTE: `serde` is used for JSON serialization, but not for CSV serialization due to the9// `parameters` map. Update `src/hyperfine/export/csv.rs` with new fields, as appropriate.10#[derive(Debug, Default, Clone, Serialize, PartialEq)]11pub struct BenchmarkResult {12 /// The command that was run13 pub command: String,1415 /// The mean run time16 pub mean: Second,1718 /// The standard deviation of all run times. Not available if only one run has been performed19 pub stddev: Option<Second>,2021 /// The median run time22 pub median: Second,2324 /// Time spend in user space25 pub user: Second,2627 /// Time spent in system space28 pub system: Second,2930 /// Min time measured31 pub min: Second,3233 /// Max time measured34 pub max: Second,3536 /// All run time measurements37 #[serde(skip_serializing_if = "Option::is_none")]38 pub times: Option<Vec<Second>>,3940 /// All run exit codes41 pub exit_codes: Vec<Option<i32>>,4243 /// Any parameter values used44 #[serde(skip_serializing_if = "BTreeMap::is_empty")]45 pub parameters: BTreeMap<String, String>,46}
modified:src/benchmark/mod.rs+2 added-503 removed
1pub mod benchmark_result;2pub mod relative_speed;2pub mod result;3pub mod scheduler;4pub mod timing_result;55use std::cmp;6use std::process::{ExitStatus, Stdio};78use colored::*;9use statistical::{mean, median, standard_deviation};1011use crate::benchmark::result::BenchmarkResult;12use crate::command::Command;13use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};14use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};15use crate::output::format::{format_duration, format_duration_unit};16use crate::output::progress_bar::get_progress_bar;17use crate::output::warnings::Warnings;18use crate::shell::execute_and_time;19use crate::timer::wallclocktimer::WallClockTimer;20use crate::timer::{TimerStart, TimerStop};21use crate::util::exit_code::extract_exit_code;22use crate::util::min_max::{max, min};6use crate::util::units::Second;725use anyhow::{bail, Result};268/// Threshold for warning about fast execution time9pub const MIN_EXECUTION_TIME: Second = 5e-3;2930/// Results from timing a single command31#[derive(Debug, Default, Copy, Clone)]32pub struct TimingResult {33 /// Wall clock time34 pub time_real: Second,3536 /// Time spent in user mode37 pub time_user: Second,3839 /// Time spent in kernel mode40 pub time_system: Second,41}4243/// Correct for shell spawning time44fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {45 if time < shell_spawning_time {46 0.047 } else {48 time - shell_spawning_time49 }50}5152/// Run the given shell command and measure the execution time53pub fn time_shell_command(54 shell: &Shell,55 command: &Command<'_>,56 command_output_policy: CommandOutputPolicy,57 failure_action: CmdFailureAction,58 shell_spawning_time: Option<TimingResult>,59) -> Result<(TimingResult, ExitStatus)> {60 let (stdout, stderr) = match command_output_policy {61 CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),62 CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),63 };6465 let wallclock_timer = WallClockTimer::start();66 let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;67 let mut time_real = wallclock_timer.stop();6869 let mut time_user = result.user_time;70 let mut time_system = result.system_time;7172 if failure_action == CmdFailureAction::RaiseError && !result.status.success() {73 bail!(74 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \75 Alternatively, use the '--show-output' option to debug what went wrong.",76 result.status.code().map_or(77 "The process has been terminated by a signal".into(),78 |c| format!("Command terminated with non-zero exit code: {}", c)79 )80 );81 }8283 // Correct for shell spawning time84 if let Some(spawning_time) = shell_spawning_time {85 time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);86 time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);87 time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);88 }8990 Ok((91 TimingResult {92 time_real,93 time_user,94 time_system,95 },96 result.status,97 ))98}99100/// Measure the average shell spawning time101pub fn mean_shell_spawning_time(102 shell: &Shell,103 style: OutputStyleOption,104 command_output_policy: CommandOutputPolicy,105) -> Result<TimingResult> {106 const COUNT: u64 = 50;107 let progress_bar = if style != OutputStyleOption::Disabled {108 Some(get_progress_bar(109 COUNT,110 "Measuring shell spawning time",111 style,112 ))113 } else {114 None115 };116117 let mut times_real: Vec<Second> = vec![];118 let mut times_user: Vec<Second> = vec![];119 let mut times_system: Vec<Second> = vec![];120121 for _ in 0..COUNT {122 // Just run the shell without any command123 let res = time_shell_command(124 shell,125 &Command::new(None, ""),126 command_output_policy,127 CmdFailureAction::RaiseError,128 None,129 );130131 match res {132 Err(_) => {133 let shell_cmd = if cfg!(windows) {134 format!("{} /C \"\"", shell)135 } else {136 format!("{} -c \"\"", shell)137 };138139 bail!(140 "Could not measure shell execution time. Make sure you can run '{}'.",141 shell_cmd142 );143 }144 Ok((r, _)) => {145 times_real.push(r.time_real);146 times_user.push(r.time_user);147 times_system.push(r.time_system);148 }149 }150151 if let Some(bar) = progress_bar.as_ref() {152 bar.inc(1)153 }154 }155156 if let Some(bar) = progress_bar.as_ref() {157 bar.finish_and_clear()158 }159160 Ok(TimingResult {161 time_real: mean(&times_real),162 time_user: mean(&times_user),163 time_system: mean(&times_system),164 })165}166167fn run_intermediate_command(168 shell: &Shell,169 command: &Option<Command<'_>>,170 command_output_policy: CommandOutputPolicy,171 error_output: &'static str,172) -> Result<TimingResult> {173 if let Some(ref cmd) = command {174 let res = time_shell_command(175 shell,176 cmd,177 command_output_policy,178 CmdFailureAction::RaiseError,179 None,180 );181 if res.is_err() {182 bail!(error_output);183 }184 return res.map(|r| r.0);185 }186 Ok(TimingResult {187 ..Default::default()188 })189}190191/// Run the command specified by `--setup`.192fn run_setup_command(193 shell: &Shell,194 command: &Option<Command<'_>>,195 output_policy: CommandOutputPolicy,196) -> Result<TimingResult> {197 let error_output = "The setup command terminated with a non-zero exit code. \198 Append ' || true' to the command if you are sure that this can be ignored.";199200 run_intermediate_command(shell, command, output_policy, error_output)201}202203/// Run the command specified by `--prepare`.204fn run_preparation_command(205 shell: &Shell,206 command: &Option<Command<'_>>,207 output_policy: CommandOutputPolicy,208) -> Result<TimingResult> {209 let error_output = "The preparation command terminated with a non-zero exit code. \210 Append ' || true' to the command if you are sure that this can be ignored.";211212 run_intermediate_command(shell, command, output_policy, error_output)213}214215/// Run the command specified by `--cleanup`.216fn run_cleanup_command(217 shell: &Shell,218 command: &Option<Command<'_>>,219 output_policy: CommandOutputPolicy,220) -> Result<TimingResult> {221 let error_output = "The cleanup command terminated with a non-zero exit code. \222 Append ' || true' to the command if you are sure that this can be ignored.";223224 run_intermediate_command(shell, command, output_policy, error_output)225}226227/// Run the benchmark for a single shell command228pub fn run_benchmark(229 num: usize,230 cmd: &Command<'_>,231 shell_spawning_time: TimingResult,232 options: &Options,233) -> Result<BenchmarkResult> {234 let command_name = cmd.get_name();235 if options.output_style != OutputStyleOption::Disabled {236 println!(237 "{}{}: {}",238 "Benchmark ".bold(),239 (num + 1).to_string().bold(),240 command_name,241 );242 }243244 let mut times_real: Vec<Second> = vec![];245 let mut times_user: Vec<Second> = vec![];246 let mut times_system: Vec<Second> = vec![];247 let mut exit_codes: Vec<Option<i32>> = vec![];248 let mut all_succeeded = true;249250 // Run init command251 let prepare_cmd = options.preparation_command.as_ref().map(|values| {252 let preparation_command = if values.len() == 1 {253 &values[0]254 } else {255 &values[num]256 };257 Command::new_parametrized(None, preparation_command, cmd.get_parameters().clone())258 });259260 // Run setup command261 let setup_cmd = options.setup_command.as_ref().map(|setup_command| {262 Command::new_parametrized(None, setup_command, cmd.get_parameters().clone())263 });264 run_setup_command(&options.shell, &setup_cmd, options.command_output_policy)?;265266 // Warmup phase267 if options.warmup_count > 0 {268 let progress_bar = if options.output_style != OutputStyleOption::Disabled {269 Some(get_progress_bar(270 options.warmup_count,271 "Performing warmup runs",272 options.output_style,273 ))274 } else {275 None276 };277278 for _ in 0..options.warmup_count {279 let _ = run_preparation_command(280 &options.shell,281 &prepare_cmd,282 options.command_output_policy,283 )?;284 let _ = time_shell_command(285 &options.shell,286 cmd,287 options.command_output_policy,288 options.command_failure_action,289 None,290 )?;291 if let Some(bar) = progress_bar.as_ref() {292 bar.inc(1)293 }294 }295 if let Some(bar) = progress_bar.as_ref() {296 bar.finish_and_clear()297 }298 }299300 // Set up progress bar (and spinner for initial measurement)301 let progress_bar = if options.output_style != OutputStyleOption::Disabled {302 Some(get_progress_bar(303 options.run_bounds.min,304 "Initial time measurement",305 options.output_style,306 ))307 } else {308 None309 };310311 let prepare_result =312 run_preparation_command(&options.shell, &prepare_cmd, options.command_output_policy)?;313314 // Initial timing run315 let (res, status) = time_shell_command(316 &options.shell,317 cmd,318 options.command_output_policy,319 options.command_failure_action,320 Some(shell_spawning_time),321 )?;322 let success = status.success();323324 // Determine number of benchmark runs325 let runs_in_min_time = (options.min_benchmarking_time326 / (res.time_real + prepare_result.time_real + shell_spawning_time.time_real))327 as u64;328329 let count = {330 let min = cmp::max(runs_in_min_time, options.run_bounds.min);331332 options333 .run_bounds334 .max335 .as_ref()336 .map(|max| cmp::min(min, *max))337 .unwrap_or(min)338 };339340 let count_remaining = count - 1;341342 // Save the first result343 times_real.push(res.time_real);344 times_user.push(res.time_user);345 times_system.push(res.time_system);346 exit_codes.push(extract_exit_code(status));347348 all_succeeded = all_succeeded && success;349350 // Re-configure the progress bar351 if let Some(bar) = progress_bar.as_ref() {352 bar.set_length(count)353 }354 if let Some(bar) = progress_bar.as_ref() {355 bar.inc(1)356 }357358 // Gather statistics359 for _ in 0..count_remaining {360 run_preparation_command(&options.shell, &prepare_cmd, options.command_output_policy)?;361362 let msg = {363 let mean = format_duration(mean(&times_real), options.time_unit);364 format!("Current estimate: {}", mean.to_string().green())365 };366367 if let Some(bar) = progress_bar.as_ref() {368 bar.set_message(msg.to_owned())369 }370371 let (res, status) = time_shell_command(372 &options.shell,373 cmd,374 options.command_output_policy,375 options.command_failure_action,376 Some(shell_spawning_time),377 )?;378 let success = status.success();379380 times_real.push(res.time_real);381 times_user.push(res.time_user);382 times_system.push(res.time_system);383 exit_codes.push(extract_exit_code(status));384385 all_succeeded = all_succeeded && success;386387 if let Some(bar) = progress_bar.as_ref() {388 bar.inc(1)389 }390 }391392 if let Some(bar) = progress_bar.as_ref() {393 bar.finish_and_clear()394 }395396 // Compute statistical quantities397 let t_num = times_real.len();398 let t_mean = mean(&times_real);399 let t_stddev = if times_real.len() > 1 {400 Some(standard_deviation(&times_real, Some(t_mean)))401 } else {402 None403 };404 let t_median = median(&times_real);405 let t_min = min(&times_real);406 let t_max = max(&times_real);407408 let user_mean = mean(&times_user);409 let system_mean = mean(&times_system);410411 // Formatting and console output412 let (mean_str, time_unit) = format_duration_unit(t_mean, options.time_unit);413 let min_str = format_duration(t_min, Some(time_unit));414 let max_str = format_duration(t_max, Some(time_unit));415 let num_str = format!("{} runs", t_num);416417 let user_str = format_duration(user_mean, Some(time_unit));418 let system_str = format_duration(system_mean, Some(time_unit));419420 if options.output_style != OutputStyleOption::Disabled {421 if times_real.len() == 1 {422 println!(423 " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",424 "abs".green().bold(),425 mean_str.green().bold(),426 " ".to_string(), // alignment427 user_str.blue(),428 system_str.blue()429 );430 } else {431 let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));432433 println!(434 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",435 "mean".green().bold(),436 "σ".green(),437 mean_str.green().bold(),438 stddev_str.green(),439 user_str.blue(),440 system_str.blue()441 );442443 println!(444 " Range ({} … {}): {:>8} … {:>8} {}",445 "min".cyan(),446 "max".purple(),447 min_str.cyan(),448 max_str.purple(),449 num_str.dimmed()450 );451 }452 }453454 // Warnings455 let mut warnings = vec![];456457 // Check execution time458 if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {459 warnings.push(Warnings::FastExecutionTime);460 }461462 // Check programm exit codes463 if !all_succeeded {464 warnings.push(Warnings::NonZeroExitCode);465 }466467 // Run outlier detection468 let scores = modified_zscores(&times_real);469 if scores[0] > OUTLIER_THRESHOLD {470 warnings.push(Warnings::SlowInitialRun(times_real[0]));471 } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {472 warnings.push(Warnings::OutliersDetected);473 }474475 if !warnings.is_empty() {476 eprintln!(" ");477478 for warning in &warnings {479 eprintln!(" {}: {}", "Warning".yellow(), warning);480 }481 }482483 if options.output_style != OutputStyleOption::Disabled {484 println!(" ");485 }486487 // Run cleanup command488 let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {489 Command::new_parametrized(None, cleanup_command, cmd.get_parameters().clone())490 });491 run_cleanup_command(&options.shell, &cleanup_cmd, options.command_output_policy)?;492493 Ok(BenchmarkResult {494 command: command_name,495 mean: t_mean,496 stddev: t_stddev,497 median: t_median,498 user: user_mean,499 system: system_mean,500 min: t_min,501 max: t_max,502 times: Some(times_real),503 exit_codes,504 parameters: cmd505 .get_parameters()506 .iter()507 .map(|(name, value)| ((*name).to_string(), value.to_string()))508 .collect(),509 })510}
modified:src/benchmark/relative_speed.rs+1 added-1 removed
1use std::cmp::Ordering;23use super::result::BenchmarkResult;3use super::benchmark_result::BenchmarkResult;4use crate::util::units::Scalar;56#[derive(Debug)]7pub struct BenchmarkResultWithRelativeSpeed<'a> {
93 unmodified lines
deleted:src/benchmark/result.rs-46 removed
1use std::collections::BTreeMap;23use serde::Serialize;45use crate::util::units::Second;67/// Set of values that will be exported.8// NOTE: `serde` is used for JSON serialization, but not for CSV serialization due to the9// `parameters` map. Update `src/hyperfine/export/csv.rs` with new fields, as appropriate.10#[derive(Debug, Default, Clone, Serialize, PartialEq)]11pub struct BenchmarkResult {12 /// The command that was run13 pub command: String,1415 /// The mean run time16 pub mean: Second,1718 /// The standard deviation of all run times. Not available if only one run has been performed19 pub stddev: Option<Second>,2021 /// The median run time22 pub median: Second,2324 /// Time spend in user space25 pub user: Second,2627 /// Time spent in system space28 pub system: Second,2930 /// Min time measured31 pub min: Second,3233 /// Max time measured34 pub max: Second,3536 /// All run time measurements37 #[serde(skip_serializing_if = "Option::is_none")]38 pub times: Option<Vec<Second>>,3940 /// All run exit codes41 pub exit_codes: Vec<Option<i32>>,4243 /// Any parameter values used44 #[serde(skip_serializing_if = "BTreeMap::is_empty")]45 pub parameters: BTreeMap<String, String>,46}
modified:src/benchmark/scheduler.rs+492 added-5 removed
1use std::cmp;2use std::process::{ExitStatus, Stdio};34use colored::*;5use statistical::{mean, median, standard_deviation};67use super::benchmark_result::BenchmarkResult;8use super::timing_result::TimingResult;9use super::{relative_speed, MIN_EXECUTION_TIME};1011use crate::command::Command;12use crate::command::Commands;13use crate::export::ExportManager;3use crate::options::{Options, OutputStyleOption};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::shell::execute_and_time;20use crate::timer::wallclocktimer::WallClockTimer;21use crate::timer::{TimerStart, TimerStop};22use crate::util::exit_code::extract_exit_code;23use crate::util::min_max::{max, min};24use crate::util::units::Second;255use super::{mean_shell_spawning_time, relative_speed, result::BenchmarkResult, run_benchmark};26use anyhow::{bail, Result};277use anyhow::Result;8use colored::*;928pub struct Scheduler<'a> {29 commands: &'a Commands<'a>,30 options: &'a Options,31 export_manager: &'a ExportManager,
75 unmodified lines
107 );108 }109 }110}111112/// Correct for shell spawning time113fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {114 if time < shell_spawning_time {115 0.0116 } else {117 time - shell_spawning_time118 }119}120121/// Run the given shell command and measure the execution time122pub fn time_shell_command(123 shell: &Shell,124 command: &Command<'_>,125 command_output_policy: CommandOutputPolicy,126 failure_action: CmdFailureAction,127 shell_spawning_time: Option<TimingResult>,128) -> Result<(TimingResult, ExitStatus)> {129 let (stdout, stderr) = match command_output_policy {130 CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),131 CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),132 };133134 let wallclock_timer = WallClockTimer::start();135 let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;136 let mut time_real = wallclock_timer.stop();137138 let mut time_user = result.user_time;139 let mut time_system = result.system_time;140141 if failure_action == CmdFailureAction::RaiseError && !result.status.success() {142 bail!(143 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \144 Alternatively, use the '--show-output' option to debug what went wrong.",145 result.status.code().map_or(146 "The process has been terminated by a signal".into(),147 |c| format!("Command terminated with non-zero exit code: {}", c)148 )149 );150 }151152 // Correct for shell spawning time153 if let Some(spawning_time) = shell_spawning_time {154 time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);155 time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);156 time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);157 }158159 Ok((160 TimingResult {161 time_real,162 time_user,163 time_system,164 },165 result.status,166 ))167}168169/// Measure the average shell spawning time170pub fn mean_shell_spawning_time(171 shell: &Shell,172 style: OutputStyleOption,173 command_output_policy: CommandOutputPolicy,174) -> Result<TimingResult> {175 const COUNT: u64 = 50;176 let progress_bar = if style != OutputStyleOption::Disabled {177 Some(get_progress_bar(178 COUNT,179 "Measuring shell spawning time",180 style,181 ))182 } else {183 None184 };185186 let mut times_real: Vec<Second> = vec![];187 let mut times_user: Vec<Second> = vec![];188 let mut times_system: Vec<Second> = vec![];189190 for _ in 0..COUNT {191 // Just run the shell without any command192 let res = time_shell_command(193 shell,194 &Command::new(None, ""),195 command_output_policy,196 CmdFailureAction::RaiseError,197 None,198 );199200 match res {201 Err(_) => {202 let shell_cmd = if cfg!(windows) {203 format!("{} /C \"\"", shell)204 } else {205 format!("{} -c \"\"", shell)206 };207208 bail!(209 "Could not measure shell execution time. Make sure you can run '{}'.",210 shell_cmd211 );212 }213 Ok((r, _)) => {214 times_real.push(r.time_real);215 times_user.push(r.time_user);216 times_system.push(r.time_system);217 }218 }219220 if let Some(bar) = progress_bar.as_ref() {221 bar.inc(1)222 }223 }224225 if let Some(bar) = progress_bar.as_ref() {226 bar.finish_and_clear()227 }228229 Ok(TimingResult {230 time_real: mean(&times_real),231 time_user: mean(&times_user),232 time_system: mean(&times_system),233 })234}235236fn run_intermediate_command(237 shell: &Shell,238 command: &Option<Command<'_>>,239 command_output_policy: CommandOutputPolicy,240 error_output: &'static str,241) -> Result<TimingResult> {242 if let Some(ref cmd) = command {243 let res = time_shell_command(244 shell,245 cmd,246 command_output_policy,247 CmdFailureAction::RaiseError,248 None,249 );250 if res.is_err() {251 bail!(error_output);252 }253 return res.map(|r| r.0);254 }255 Ok(TimingResult {256 ..Default::default()257 })258}259260/// Run the command specified by `--setup`.261fn run_setup_command(262 shell: &Shell,263 command: &Option<Command<'_>>,264 output_policy: CommandOutputPolicy,265) -> Result<TimingResult> {266 let error_output = "The setup command terminated with a non-zero exit code. \267 Append ' || true' to the command if you are sure that this can be ignored.";268269 run_intermediate_command(shell, command, output_policy, error_output)270}271272/// Run the command specified by `--prepare`.273fn run_preparation_command(274 shell: &Shell,275 command: &Option<Command<'_>>,276 output_policy: CommandOutputPolicy,277) -> Result<TimingResult> {278 let error_output = "The preparation command terminated with a non-zero exit code. \279 Append ' || true' to the command if you are sure that this can be ignored.";280281 run_intermediate_command(shell, command, output_policy, error_output)282}283284/// Run the command specified by `--cleanup`.285fn run_cleanup_command(286 shell: &Shell,287 command: &Option<Command<'_>>,288 output_policy: CommandOutputPolicy,289) -> Result<TimingResult> {290 let error_output = "The cleanup command terminated with a non-zero exit code. \291 Append ' || true' to the command if you are sure that this can be ignored.";292293 run_intermediate_command(shell, command, output_policy, error_output)294}295296/// Run the benchmark for a single shell command297pub fn run_benchmark(298 num: usize,299 cmd: &Command<'_>,300 shell_spawning_time: TimingResult,301 options: &Options,302) -> Result<BenchmarkResult> {303 let command_name = cmd.get_name();304 if options.output_style != OutputStyleOption::Disabled {305 println!(306 "{}{}: {}",307 "Benchmark ".bold(),308 (num + 1).to_string().bold(),309 command_name,310 );311 }312313 let mut times_real: Vec<Second> = vec![];314 let mut times_user: Vec<Second> = vec![];315 let mut times_system: Vec<Second> = vec![];316 let mut exit_codes: Vec<Option<i32>> = vec![];317 let mut all_succeeded = true;318319 // Run init command320 let prepare_cmd = options.preparation_command.as_ref().map(|values| {321 let preparation_command = if values.len() == 1 {322 &values[0]323 } else {324 &values[num]325 };326 Command::new_parametrized(None, preparation_command, cmd.get_parameters().clone())327 });328329 // Run setup command330 let setup_cmd = options.setup_command.as_ref().map(|setup_command| {331 Command::new_parametrized(None, setup_command, cmd.get_parameters().clone())332 });333 run_setup_command(&options.shell, &setup_cmd, options.command_output_policy)?;334335 // Warmup phase336 if options.warmup_count > 0 {337 let progress_bar = if options.output_style != OutputStyleOption::Disabled {338 Some(get_progress_bar(339 options.warmup_count,340 "Performing warmup runs",341 options.output_style,342 ))343 } else {344 None345 };346347 for _ in 0..options.warmup_count {348 let _ = run_preparation_command(349 &options.shell,350 &prepare_cmd,351 options.command_output_policy,352 )?;353 let _ = time_shell_command(354 &options.shell,355 cmd,356 options.command_output_policy,357 options.command_failure_action,358 None,359 )?;360 if let Some(bar) = progress_bar.as_ref() {361 bar.inc(1)362 }363 }364 if let Some(bar) = progress_bar.as_ref() {365 bar.finish_and_clear()366 }367 }368369 // Set up progress bar (and spinner for initial measurement)370 let progress_bar = if options.output_style != OutputStyleOption::Disabled {371 Some(get_progress_bar(372 options.run_bounds.min,373 "Initial time measurement",374 options.output_style,375 ))376 } else {377 None378 };379380 let prepare_result =381 run_preparation_command(&options.shell, &prepare_cmd, options.command_output_policy)?;382383 // Initial timing run384 let (res, status) = time_shell_command(385 &options.shell,386 cmd,387 options.command_output_policy,388 options.command_failure_action,389 Some(shell_spawning_time),390 )?;391 let success = status.success();392393 // Determine number of benchmark runs394 let runs_in_min_time = (options.min_benchmarking_time395 / (res.time_real + prepare_result.time_real + shell_spawning_time.time_real))396 as u64;397398 let count = {399 let min = cmp::max(runs_in_min_time, options.run_bounds.min);400401 options402 .run_bounds403 .max404 .as_ref()405 .map(|max| cmp::min(min, *max))406 .unwrap_or(min)407 };408409 let count_remaining = count - 1;410411 // Save the first result412 times_real.push(res.time_real);413 times_user.push(res.time_user);414 times_system.push(res.time_system);415 exit_codes.push(extract_exit_code(status));416417 all_succeeded = all_succeeded && success;418419 // Re-configure the progress bar420 if let Some(bar) = progress_bar.as_ref() {421 bar.set_length(count)422 }423 if let Some(bar) = progress_bar.as_ref() {424 bar.inc(1)425 }426427 // Gather statistics428 for _ in 0..count_remaining {429 run_preparation_command(&options.shell, &prepare_cmd, options.command_output_policy)?;430431 let msg = {432 let mean = format_duration(mean(&times_real), options.time_unit);433 format!("Current estimate: {}", mean.to_string().green())434 };435436 if let Some(bar) = progress_bar.as_ref() {437 bar.set_message(msg.to_owned())438 }439440 let (res, status) = time_shell_command(441 &options.shell,442 cmd,443 options.command_output_policy,444 options.command_failure_action,445 Some(shell_spawning_time),446 )?;447 let success = status.success();448449 times_real.push(res.time_real);450 times_user.push(res.time_user);451 times_system.push(res.time_system);452 exit_codes.push(extract_exit_code(status));453454 all_succeeded = all_succeeded && success;455456 if let Some(bar) = progress_bar.as_ref() {457 bar.inc(1)458 }459 }460461 if let Some(bar) = progress_bar.as_ref() {462 bar.finish_and_clear()463 }464465 // Compute statistical quantities466 let t_num = times_real.len();467 let t_mean = mean(&times_real);468 let t_stddev = if times_real.len() > 1 {469 Some(standard_deviation(&times_real, Some(t_mean)))470 } else {471 None472 };473 let t_median = median(&times_real);474 let t_min = min(&times_real);475 let t_max = max(&times_real);476477 let user_mean = mean(&times_user);478 let system_mean = mean(&times_system);479480 // Formatting and console output481 let (mean_str, time_unit) = format_duration_unit(t_mean, options.time_unit);482 let min_str = format_duration(t_min, Some(time_unit));483 let max_str = format_duration(t_max, Some(time_unit));484 let num_str = format!("{} runs", t_num);485486 let user_str = format_duration(user_mean, Some(time_unit));487 let system_str = format_duration(system_mean, Some(time_unit));488489 if options.output_style != OutputStyleOption::Disabled {490 if times_real.len() == 1 {491 println!(492 " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",493 "abs".green().bold(),494 mean_str.green().bold(),495 " ".to_string(), // alignment496 user_str.blue(),497 system_str.blue()498 );499 } else {500 let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));501502 println!(503 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",504 "mean".green().bold(),505 "σ".green(),506 mean_str.green().bold(),507 stddev_str.green(),508 user_str.blue(),509 system_str.blue()510 );511512 println!(513 " Range ({} … {}): {:>8} … {:>8} {}",514 "min".cyan(),515 "max".purple(),516 min_str.cyan(),517 max_str.purple(),518 num_str.dimmed()519 );520 }521 }522523 // Warnings524 let mut warnings = vec![];525526 // Check execution time527 if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {528 warnings.push(Warnings::FastExecutionTime);529 }530531 // Check programm exit codes532 if !all_succeeded {533 warnings.push(Warnings::NonZeroExitCode);534 }535536 // Run outlier detection537 let scores = modified_zscores(&times_real);538 if scores[0] > OUTLIER_THRESHOLD {539 warnings.push(Warnings::SlowInitialRun(times_real[0]));540 } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {541 warnings.push(Warnings::OutliersDetected);542 }543544 if !warnings.is_empty() {545 eprintln!(" ");546547 for warning in &warnings {548 eprintln!(" {}: {}", "Warning".yellow(), warning);549 }550 }551552 if options.output_style != OutputStyleOption::Disabled {553 println!(" ");554 }555556 // Run cleanup command557 let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {558 Command::new_parametrized(None, cleanup_command, cmd.get_parameters().clone())559 });560 run_cleanup_command(&options.shell, &cleanup_cmd, options.command_output_policy)?;561562 Ok(BenchmarkResult {563 command: command_name,564 mean: t_mean,565 stddev: t_stddev,566 median: t_median,567 user: user_mean,568 system: system_mean,569 min: t_min,570 max: t_max,571 times: Some(times_real),572 exit_codes,573 parameters: cmd574 .get_parameters()575 .iter()576 .map(|(name, value)| ((*name).to_string(), value.to_string()))577 .collect(),578 })579}
added:src/benchmark/timing_result.rs+14 added
1use crate::util::units::Second;23/// Results from timing a single command4#[derive(Debug, Default, Copy, Clone)]5pub struct TimingResult {6 /// Wall clock time7 pub time_real: Second,89 /// Time spent in user mode10 pub time_user: Second,1112 /// Time spent in kernel mode13 pub time_system: Second,14}
modified:src/export/asciidoc.rs+1 added-1 removed
1use crate::benchmark::benchmark_result::BenchmarkResult;2use crate::benchmark::relative_speed::{self, BenchmarkResultWithRelativeSpeed};2use crate::benchmark::result::BenchmarkResult;3use crate::output::format::format_duration_value;4use crate::util::units::Unit;56use super::Exporter;
267 unmodified lines
modified:src/export/csv.rs+1 added-1 removed
1 unmodified line
23use csv::WriterBuilder;45use super::Exporter;6use crate::benchmark::result::BenchmarkResult;6use crate::benchmark::benchmark_result::BenchmarkResult;7use crate::util::units::Unit;89use anyhow::Result;10
100 unmodified lines
modified:src/export/json.rs+1 added-1 removed
1use serde::*;2use serde_json::to_vec_pretty;34use super::Exporter;5use crate::benchmark::result::BenchmarkResult;5use crate::benchmark::benchmark_result::BenchmarkResult;6use crate::util::units::Unit;78use anyhow::Result;9
18 unmodified lines
modified:src/export/markdown.rs+1 added-1 removed
1use super::Exporter;2use crate::benchmark::benchmark_result::BenchmarkResult;3use crate::benchmark::relative_speed::{self, BenchmarkResultWithRelativeSpeed};3use crate::benchmark::result::BenchmarkResult;4use crate::output::format::format_duration_value;5use crate::util::units::Unit;67use anyhow::{anyhow, Result};
286 unmodified lines
modified:src/export/mod.rs+1 added-1 removed
9 unmodified lines
10use self::csv::CsvExporter;11use self::json::JsonExporter;12use self::markdown::MarkdownExporter;1314use crate::benchmark::result::BenchmarkResult;14use crate::benchmark::benchmark_result::BenchmarkResult;15use crate::util::units::Unit;1617use anyhow::{Context, Result};18use clap::ArgMatches;
89 unmodified lines