Simplify run creation
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 c20fcc0 · Browse files · 5 files·+153 added−128 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+153 added−128 removed
- other:+153 added−128 removed
Provenance
- Commit
f7e6d72- Tree
fa024af- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
David Peter <mail@david-peter.de>- Parent
c20fcc0
5 files changed+153 added−128 removed
modified:src/benchmark/benchmark_result.rs+84 added-30 removed
25 unmodified lines26 /// Exit codes of the process27 pub exit_code: Option<i32>,28 }29 30-/// Parameter value and whether it was used in the command line template30 #[derive(Debug, Default, Clone, Serialize, PartialEq)]32-pub struct Parameter {33- pub value: String,34- pub is_unused: bool,31+pub struct Runs {32+ pub runs: Vec<Run>,33 }34 37-/// Meta data and performance metrics for a single benchmark38-#[derive(Debug, Default, Clone, Serialize, PartialEq)]39-#[serde(transparent)]40-pub struct Parameter {41- pub value: String,42- #[serde(skip)]43- pub is_unused: bool,44-}35+impl Runs {36+ pub fn new(runs: Vec<Run>) -> Self {37+ Self { runs }38+ }39 46-/// Meta data and performance metrics for a single benchmark47-#[derive(Debug, Default, Clone, PartialEq)]48-pub struct BenchmarkResult {49- /// The full command line of the program that is being benchmarked50- pub command: String,40+ pub fn len(&self) -> usize {41+ self.runs.len()42+ }43 52- /// Performance metrics and exit codes for each run53- pub runs: Vec<Run>,44+ pub fn is_empty(&self) -> bool {45+ self.runs.is_empty()46+ }47 55- /// Parameter values for this benchmark56- #[serde(skip_serializing_if = "BTreeMap::is_empty")]57- pub parameters: BTreeMap<String, Parameter>,58-}48+ pub fn push(&mut self, run: Run) {49+ self.runs.push(run);50+ }51 60-impl BenchmarkResult {61- fn wall_clock_times(&self) -> Vec<Second> {52+ pub fn wall_clock_times(&self) -> Vec<Second> {53 self.runs.iter().map(|run| run.wall_clock_time).collect()54 }55 65- /// The average run time56+ /// The average wall clock time57 pub fn mean(&self) -> Second {58 mean(&self.wall_clock_times())59 }60 70- /// The standard deviation of all run times. Not available if only one run has been performed61+ /// The standard deviation of all wall clock times. Not available if only one run has been performed62 pub fn stddev(&self) -> Option<Second> {63 let times = self.wall_clock_times();64 65 let t_mean = mean(×);3 unmodified lines69 None70 }71 }72 82- /// The median run time73+ /// The median wall clock time74 pub fn median(&self) -> Second {75 median(&self.wall_clock_times())76 }77 87- /// The minimum run time78+ /// The minimum wall clock time79 pub fn min(&self) -> Second {80 min(&self.wall_clock_times())81 }82 92- /// The maximum run time83+ /// The maximum wall clock time84 pub fn max(&self) -> Second {85 max(&self.wall_clock_times())86 }87 88+ /// The average user time89 pub fn user_mean(&self) -> Second {90 mean(91 &self92 .runs2 unmodified lines95 .collect::<Vec<_>>(),96 )97 }98 99+ /// The average system time100 pub fn system_mean(&self) -> Second {101 mean(102 &self103 .runs1 unmodified line105 .map(|run| run.system_time)106 .collect::<Vec<_>>(),107 )108 }109+}110 111+/// Parameter value and whether it was used in the command line template112+#[derive(Debug, Default, Clone, Serialize, PartialEq)]113+pub struct Parameter {114+ pub value: String,115+ pub is_unused: bool,116+}117+118+/// Meta data and performance metrics for a single benchmark119+#[derive(Debug, Default, Clone, Serialize, PartialEq)]120+#[serde(transparent)]121+pub struct Parameter {122+ pub value: String,123+ #[serde(skip)]124+ pub is_unused: bool,125+}126+127+/// Meta data and performance metrics for a single benchmark128+#[derive(Debug, Default, Clone, PartialEq)]129+pub struct BenchmarkResult {130+ /// The full command line of the program that is being benchmarked131+ pub command: String,132+133+ /// Performance metrics and exit codes for each run134+ #[serde(flatten)]135+ pub runs: Runs,136+137+ /// Parameter values for this benchmark138+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]139+ pub parameters: BTreeMap<String, Parameter>,140+}141+142+impl BenchmarkResult {143+ pub fn mean(&self) -> Second {144+ self.runs.mean()145+ }146+147+ pub fn stddev(&self) -> Option<Second> {148+ self.runs.stddev()149+ }150+151+ pub fn median(&self) -> Second {152+ self.runs.median()153+ }154+155+ pub fn min(&self) -> Second {156+ self.runs.min()157+ }158+159+ pub fn max(&self) -> Second {160+ self.runs.max()161+ }162+163+ pub fn user_mean(&self) -> Second {164+ self.runs.user_mean()165+ }166+167+ pub fn system_mean(&self) -> Second {168+ self.runs.system_mean()169+ }170+171 /// The full command line of the program that is being benchmarked, possibly including a list of172 /// parameters that were not used in the command line template.173 pub fn command_with_unused_parameters(&self) -> String {174 let parameters = self16 unmodified linesmodified:src/benchmark/mod.rs+37 added-68 removed
6 unmodified lines7 use std::cmp;8 use std::io::{self, Write};9 use std::time::Instant;10 11-use crate::benchmark::benchmark_result::{Parameter, Run};11+use crate::benchmark::benchmark_result::{Parameter, Run, Runs};12 use crate::benchmark::executor::BenchmarkIteration;13 use crate::command::Command;14 use crate::options::{15 CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,4 unmodified lines20 finish_initial_measurement, get_progress_bar, start_initial_measurement,21 };22 use crate::output::warnings::{OutlierWarningOptions, Warnings};23 use crate::parameter::ParameterNameAndValue;24-use crate::quantity::{const_time_from_seconds, ratio, FormatQuantity, Time, Zero};25-use benchmark_result::{BenchmarkResult, Parameter};24+use crate::quantity::{byte, const_time_from_seconds, ratio, second, FormatQuantity, Time, Zero};25+use crate::util::exit_code::extract_exit_code;26+use crate::util::units::Second;27+use benchmark_result::BenchmarkResult;28 use measurement::{Measurement, Measurements};29 30 use anyhow::{anyhow, Result};31 use colored::*;30-use statistical::{mean, standard_deviation};32 33 use self::executor::Executor;34 35 /// Threshold for warning about fast execution time132 unmodified lines168 self.command.get_name_with_unused_parameters(),169 )?;170 }171 171- let mut times_wall_clock: Vec<Second> = vec![];172- let mut times_user: Vec<Second> = vec![];173- let mut times_system: Vec<Second> = vec![];174- let mut memory_usage_byte: Vec<u64> = vec![];175- let mut exit_codes: Vec<Option<i32>> = vec![];172+ let mut runs = Runs::default();173 let mut all_succeeded = true;174 175 let output_policy = &self.options.command_output_policies[self.number];176 139 unmodified lines316 317 let count_remaining = count - 1;318 319 // Save the first result323- times_wall_clock.push(res.time_wall_clock);324- times_user.push(res.time_user);325- times_system.push(res.time_system);326- memory_usage_byte.push(res.memory_usage_byte);327- exit_codes.push(extract_exit_code(status));320+ runs.push(Run {321+ wall_clock_time: res.time_wall_clock,322+ user_time: res.time_user,323+ system_time: res.time_system,324+ memory_usage_byte: res.memory_usage_byte,325+ exit_code: extract_exit_code(status),326+ });327 328 all_succeeded = all_succeeded && success;329 330 // Re-configure the progress bar6 unmodified lines337 for i in 0..count_remaining {338 let benchmark_iteration = BenchmarkIteration::Benchmark(i + 1);339 340 let msg = {342- let mean = format_duration(mean(×_wall_clock), self.options.time_unit);341+ let mean = format_duration(runs.mean(), self.options.time_unit);342 format!("Current estimate: {}", mean.to_string().green())343 };344 345 if let Some(bar) = progress_bar.as_ref() {9 unmodified lines355 output_policy,356 )?;357 let success = res.exit_status.success();358 360- times_wall_clock.push(res.time_wall_clock);361- times_user.push(res.time_user);362- times_system.push(res.time_system);363- memory_usage_byte.push(res.memory_usage_byte);364- exit_codes.push(extract_exit_code(status));359+ runs.push(Run {360+ wall_clock_time: res.time_wall_clock,361+ user_time: res.time_user,362+ system_time: res.time_system,363+ memory_usage_byte: res.memory_usage_byte,364+ exit_code: extract_exit_code(status),365+ });366 367 all_succeeded = all_succeeded && success;368 369 if let Some(bar) = progress_bar.as_ref() {6 unmodified lines376 if let Some(bar) = progress_bar.as_ref() {377 bar.finish_and_clear()378 }379 379- // Compute statistical quantities380- let t_num = times_wall_clock.len();381- let t_mean = mean(×_wall_clock);382- let t_stddev = if times_wall_clock.len() > 1 {383- Some(standard_deviation(×_wall_clock, Some(t_mean)))384- } else {385- None386- };387- let t_min = min(×_wall_clock);388- let t_max = max(×_wall_clock);389-390- let user_mean = measurements.time_user_mean();391- let system_mean = measurements.time_system_mean();392-380 // Formatting and console output394- let time_unit = self.options.time_unit.unwrap_or(t_mean.suitable_unit());395- let mean_str = t_mean.format(time_unit);396- let min_str = t_min.format(time_unit);397- let max_str = t_max.format(time_unit);398- let num_str = format!("{t_num} runs");381+ let (mean_str, time_unit) = format_duration_unit(runs.mean(), self.options.time_unit);382+ let min_str = format_duration(runs.min(), Some(time_unit));383+ let max_str = format_duration(runs.max(), Some(time_unit));384+ let num_str = format!("{num_runs} runs", num_runs = runs.len());385 400- let user_str = user_mean.format(time_unit);401- let system_str = system_mean.format(time_unit);386+ let user_str = format_duration(runs.user_mean(), Some(time_unit));387+ let system_str = format_duration(runs.system_mean(), Some(time_unit));388 389 if self.options.output_style != OutputStyleOption::Disabled {404- if times_wall_clock.len() == 1 {390+ if runs.len() == 1 {391 println!(392 " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",393 "abs".green().bold(),394 mean_str.green().bold(),1 unmodified line396 user_str.blue(),397 system_str.blue()398 )?;399 } else {414- let stddev_str = t_stddev.unwrap().format(time_unit);400+ let stddev_str = format_duration(runs.stddev().unwrap(), Some(time_unit));401 402 console_writeln!(403 stdout,404 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",21 unmodified lines426 let mut warnings = vec![];427 428 // Check execution time429 if matches!(self.options.executor_kind, ExecutorKind::Shell(_))430+ && runs431+ .wall_clock_times()432+ .iter()444- && times_wall_clock.iter().any(|&t| t < MIN_EXECUTION_TIME)433+ .any(|&t| t < MIN_EXECUTION_TIME)434 {435 warnings.push(Warnings::FastExecutionTime);436 }437 2 unmodified lines440 warnings.push(Warnings::NonZeroExitCode);441 }442 443 // Run outlier detection455- let scores = modified_zscores(×_wall_clock);444+ let scores = modified_zscores(&runs.wall_clock_times());445 446 let outlier_warning_options = OutlierWarningOptions {447 warmup_in_use: self.options.warmup_count > 0,448 prepare_in_use: self6 unmodified lines455 };456 457 if scores[0] > OUTLIER_THRESHOLD {458 warnings.push(Warnings::SlowInitialRun(470- times_wall_clock[0],459+ runs.wall_clock_times()[0],460 outlier_warning_options,461 ));462 } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {463 warnings.push(Warnings::OutliersDetected(outlier_warning_options));15 unmodified lines479 self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;480 481 Ok(BenchmarkResult {482 command: self.command.get_name(),494- runs: times_wall_clock495- .iter()496- .zip(times_user.iter())497- .zip(times_system.iter())498- .zip(memory_usage_byte.iter())499- .zip(exit_codes.iter())500- .map(501- |(502- (((wall_clock_time, user_time), system_time), memory_usage_byte),503- exit_code,504- )| {505- Run {506- wall_clock_time: *wall_clock_time,507- user_time: *user_time,508- system_time: *system_time,509- memory_usage_byte: *memory_usage_byte,510- exit_code: *exit_code,511- }512- },513- )514- .collect(),483+ runs,484 parameters: self485 .command486 .get_parameters()487 .iter()1 unmodified line489 (490 name.to_string(),491 Parameter {492 value: value.to_string(),524- is_unused: self.command.is_parameter_unused(&name),493+ is_unused: self.command.is_parameter_unused(name),494 },495 )496 })497 .collect(),3 unmodified linesmodified:src/benchmark/relative_speed.rs+10 added-8 removed
145 unmodified lines146 #[cfg(test)]147 fn create_result(name: &str, mean: f64) -> BenchmarkResult {148 use std::collections::BTreeMap;149 150- use crate::benchmark::benchmark_result::Run;150+ use crate::benchmark::benchmark_result::{Run, Runs};151 152 BenchmarkResult {153 command: name.into(),154+ runs: Runs {154- runs: vec![Run {155- wall_clock_time: mean,156- user_time: mean,157- system_time: 0.,158- memory_usage_byte: 1024,159- exit_code: Some(0),160- }],155+ runs: vec![Run {156+ wall_clock_time: mean,157+ user_time: mean,158+ system_time: 0.,159+ memory_usage_byte: 1024,160+ exit_code: Some(0),161+ }],162+ },163 parameters: BTreeMap::new(),164 }165 }166 64 unmodified linesmodified:src/export/csv.rs+5 added-5 removed
66 unmodified lines67 }68 }69 70 #[cfg(test)]71-use crate::benchmark::benchmark_result::{Parameter, Run};71+use crate::benchmark::benchmark_result::{Parameter, Run, Runs};72 73 #[test]74 fn test_csv() {75 use crate::benchmark::benchmark_result::Parameter;7 unmodified lines83 84 let results = vec![85 BenchmarkResult {86 command: String::from("command_a"),87- runs: vec![87+ runs: Runs::new(vec![88 Run {89 wall_clock_time: 7.0,90 user_time: 7.0,91 system_time: 0.0,13 unmodified lines105 system_time: 0.0,106 memory_usage_byte: 1024,107 exit_code: Some(0),108 },109- ],109+ ]),110 parameters: {111 let mut params = BTreeMap::new();112 params.insert(113 "foo".into(),13 unmodified lines127 },128 },129 BenchmarkResult {130 command: String::from("command_b"),131- runs: vec![131+ runs: Runs::new(vec![132 Run {133 wall_clock_time: 17.0,134 user_time: 17.0,135 system_time: 0.0,13 unmodified lines149 system_time: 0.0,150 memory_usage_byte: 1024,151 exit_code: Some(0),152 },153- ],153+ ]),154 parameters: {155 let mut params = BTreeMap::new();156 params.insert(157 "foo".into(),30 unmodified linesmodified:src/export/tests.rs+17 added-17 removed
1 use super::Exporter;2-use crate::benchmark::benchmark_result::{BenchmarkResult, Run};2+use crate::benchmark::benchmark_result::{BenchmarkResult, Run, Runs};3 use crate::export::asciidoc::AsciidocExporter;4 use crate::export::orgmode::OrgmodeExporter;5 use crate::quantity::{byte, second, Information, Time, TimeUnit, Zero};6 use crate::{export::markdown::MarkdownExporter, options::SortOrder};19 unmodified lines26 fn test_markup_export_auto_ms() {27 let results = [28 BenchmarkResult {29 command: String::from("sleep 0.1"),30- runs: vec![30+ runs: Runs::new(vec![31 Run {32 wall_clock_time: 0.09,33 user_time: 0.09,34 system_time: 0.,13 unmodified lines48 system_time: 0.,49 memory_usage_byte: 1024,50 exit_code: Some(0),51 },52- ],52+ ]),53 parameters: BTreeMap::new(),54 },55 BenchmarkResult {56 command: String::from("sleep 2"),57- runs: vec![57+ runs: Runs::new(vec![58 Run {59 wall_clock_time: 2.0,60 user_time: 2.0,61 system_time: 0.,13 unmodified lines75 system_time: 0.,76 memory_usage_byte: 1024,77 exit_code: Some(0),78 },79- ],79+ ]),80 parameters: BTreeMap::new(),81 },82 ];83 41 unmodified lines125 fn test_markup_export_auto_s() {126 let results = [127 BenchmarkResult {128 command: String::from("sleep 2"),129- runs: vec![129+ runs: Runs::new(vec![130 Run {131 wall_clock_time: 2.1,132 user_time: 2.1,133 system_time: 0.,13 unmodified lines147 system_time: 0.,148 memory_usage_byte: 1024,149 exit_code: Some(0),150 },151- ],151+ ]),152 parameters: BTreeMap::new(),153 },154 BenchmarkResult {155 command: String::from("sleep 0.1"),156- runs: vec![156+ runs: Runs::new(vec![157 Run {158 wall_clock_time: 0.1,159 user_time: 0.1,160 system_time: 0.,13 unmodified lines174 system_time: 0.,175 memory_usage_byte: 1024,176 exit_code: Some(0),177 },178- ],178+ ]),179 parameters: BTreeMap::new(),180 },181 ];182 41 unmodified lines224 fn test_markup_export_manual_ms() {225 let timing_results = [226 BenchmarkResult {227 command: String::from("sleep 2"),228- runs: vec![228+ runs: Runs::new(vec![229 Run {230 wall_clock_time: 2.1,231 user_time: 2.1,232 system_time: 0.,13 unmodified lines246 system_time: 0.,247 memory_usage_byte: 1024,248 exit_code: Some(0),249 },250- ],250+ ]),251 parameters: BTreeMap::new(),252 },253 BenchmarkResult {254 command: String::from("sleep 0.1"),255- runs: vec![255+ runs: Runs::new(vec![256 Run {257 wall_clock_time: 0.1,258 user_time: 0.1,259 system_time: 0.,13 unmodified lines273 system_time: 0.,274 memory_usage_byte: 1024,275 exit_code: Some(0),276 },277- ],277+ ]),278 parameters: BTreeMap::new(),279 },280 ];281 40 unmodified lines322 fn test_markup_export_manual_s() {323 let results = [324 BenchmarkResult {325 command: String::from("sleep 2"),326- runs: vec![326+ runs: Runs::new(vec![327 Run {328 wall_clock_time: 2.01,329 user_time: 2.01,330 system_time: 0.,13 unmodified lines344 system_time: 0.,345 memory_usage_byte: 1024,346 exit_code: Some(0),347 },348- ],348+ ]),349 parameters: BTreeMap::new(),350 },351 BenchmarkResult {352 command: String::from("sleep 0.1"),353- runs: vec![353+ runs: Runs::new(vec![354 Run {355 wall_clock_time: 0.11,356 user_time: 0.11,357 system_time: 0.,13 unmodified lines371 system_time: 0.,372 memory_usage_byte: 1024,373 exit_code: Some(0),374 },375- ],375+ ]),376 parameters: BTreeMap::new(),377 },378 ];379 37 unmodified lines