Added option to manually specify a reference to compare the results to.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Jan-Eric Nitschke · committed by David Peter · parent 4a00f18 · Browse files · 5 files·+78 added−21 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+78 added−21 removed
- other:+78 added−21 removed
Provenance
- Commit
9806ed7- Tree
bd46c7e- Author
Jan-Eric Nitschke <47750513+JanEricNitschke@users.noreply.github.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
4a00f18
5 files changed+78 added−21 removed
modified:src/benchmark/relative_speed.rs+31 added-10 removed
6 unmodified lines7 pub struct BenchmarkResultWithRelativeSpeed<'a> {8 pub result: &'a BenchmarkResult,9 pub relative_speed: Scalar,10 pub relative_speed_stddev: Option<Scalar>,11- pub is_fastest: bool,11+ pub is_reference: bool,12+ // Less means faster13+ pub relative_ordering: Ordering,14 }15 16 pub fn compare_mean_time(l: &BenchmarkResult, r: &BenchmarkResult) -> Ordering {17 l.mean.partial_cmp(&r.mean).unwrap_or(Ordering::Equal)18 }19 18-fn fastest_of(results: &[BenchmarkResult]) -> &BenchmarkResult {20+pub fn fastest_of(results: &[BenchmarkResult]) -> &BenchmarkResult {21 results22 .iter()23 .min_by(|&l, &r| compare_mean_time(l, r))24 .expect("at least one benchmark result")25 }26 27 fn compute_relative_speeds<'a>(28 results: &'a [BenchmarkResult],27- fastest: &'a BenchmarkResult,29+ reference: &'a BenchmarkResult,30 sort_order: SortOrder,31 ) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> {32 let mut results: Vec<_> = results33 .iter()34 .map(|result| {33- let is_fastest = result == fastest;35+ let is_reference = result == reference;36+ let relative_ordering = compare_mean_time(result, reference);37 38 if result.mean == 0.0 {39 return BenchmarkResultWithRelativeSpeed {40 result,38- relative_speed: if is_fastest { 1.0 } else { f64::INFINITY },41+ relative_speed: if is_reference { 1.0 } else { f64::INFINITY },42 relative_speed_stddev: None,40- is_fastest,43+ is_reference,44+ relative_ordering,45 };46 }47 44- let ratio = result.mean / fastest.mean;48+ let ratio = match relative_ordering {49+ Ordering::Less => reference.mean / result.mean,50+ Ordering::Equal => 1.0,51+ Ordering::Greater => result.mean / reference.mean,52+ };53 54 // https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas55 // Covariance asssumed to be 0, i.e. variables are assumed to be independent48- let ratio_stddev = match (result.stddev, fastest.stddev) {56+ let ratio_stddev = match (result.stddev, reference.stddev) {57 (Some(result_stddev), Some(fastest_stddev)) => Some(58 ratio59 * ((result_stddev / result.mean).powi(2)52- + (fastest_stddev / fastest.mean).powi(2))60+ + (fastest_stddev / reference.mean).powi(2))61 .sqrt(),62 ),63 _ => None,64 };1 unmodified line66 BenchmarkResultWithRelativeSpeed {67 result,68 relative_speed: ratio,69 relative_speed_stddev: ratio_stddev,62- is_fastest,70+ is_reference,71+ relative_ordering,72 }73 })74 .collect();75 6 unmodified lines82 83 results84 }85 86+pub fn compute_with_check_from_reference<'a>(87+ results: &'a [BenchmarkResult],88+ reference: &'a BenchmarkResult,89+ sort_order: SortOrder,90+) -> Option<Vec<BenchmarkResultWithRelativeSpeed<'a>>> {91+ if fastest_of(results).mean == 0.0 || reference.mean == 0.0 {92+ return None;93+ }94+95+ Some(compute_relative_speeds(results, reference, sort_order))96+}97+98 pub fn compute_with_check(99 results: &[BenchmarkResult],100 sort_order: SortOrder,101 ) -> Option<Vec<BenchmarkResultWithRelativeSpeed>> {64 unmodified linesmodified:src/benchmark/scheduler.rs+30 added-10 removed
1-use colored::*;2-1 use super::benchmark_result::BenchmarkResult;2 use super::executor::{Executor, MockExecutor, RawExecutor, ShellExecutor};3 use super::{relative_speed, Benchmark};4+use colored::*;5+use std::cmp::Ordering;6 7-use crate::command::Commands;7+use crate::command::{Command, Commands};8 use crate::export::ExportManager;9 use crate::options::{ExecutorKind, Options, OutputStyleOption, SortOrder};10 11 use anyhow::Result;25 unmodified lines37 ExecutorKind::Mock(ref shell) => Box::new(MockExecutor::new(shell.clone())),38 ExecutorKind::Shell(ref shell) => Box::new(ShellExecutor::new(shell, self.options)),39 };40 41+ let reference = self42+ .options43+ .reference_command44+ .as_ref()45+ .map(|cmd| Command::new(None, cmd));46+47 executor.calibrate()?;48 43- for (number, cmd) in self.commands.iter().enumerate() {49+ for (number, cmd) in reference.iter().chain(self.commands.iter()).enumerate() {50 self.results51 .push(Benchmark::new(number, cmd, self.options, &*executor).run()?);52 53 // We export results after each individual benchmark, because16 unmodified lines70 if self.results.len() < 2 {71 return;72 }73 74+ let reference = self75+ .options76+ .reference_command77+ .as_ref()78+ .map(|_| &self.results[0])79+ .unwrap_or_else(|| relative_speed::fastest_of(&self.results));80+68- if let Some(annotated_results) = relative_speed::compute_with_check(81+ if let Some(annotated_results) = relative_speed::compute_with_check_from_reference(82 &self.results,83+ reference,84 self.options.sort_order_speed_comparison,85 ) {86 match self.options.sort_order_speed_comparison {87 SortOrder::MeanTime => {88 println!("{}", "Summary".bold());89 76- let fastest = annotated_results.iter().find(|r| r.is_fastest).unwrap();77- let others = annotated_results.iter().filter(|r| !r.is_fastest);90+ let reference = annotated_results.iter().find(|r| r.is_reference).unwrap();91+ let others = annotated_results.iter().filter(|r| !r.is_reference);92 93 println!(94 " {} ran",81- fastest.result.command_with_unused_parameters.cyan()95+ reference.result.command_with_unused_parameters.cyan()96 );97 98 for item in others {99+ let comparator = match item.relative_ordering {100+ Ordering::Less => "slower",101+ Ordering::Greater => "faster",102+ Ordering::Equal => "as fast",103+ };104 println!(86- "{}{} times faster than {}",105+ "{}{} times {} than {}",106 format!("{:8.2}", item.relative_speed).bold().green(),107 if let Some(stddev) = item.relative_speed_stddev {108 format!(" ± {}", format!("{stddev:.2}").green())109 } else {110 "".into()111 },112+ comparator,113 &item.result.command_with_unused_parameters.magenta()114 );115 }116 }3 unmodified lines120 for item in annotated_results {121 println!(122 " {}{} {}",123 format!("{:10.2}", item.relative_speed).bold().green(),104- if item.is_fastest {124+ if item.is_reference {125 " ".into()126 } else if let Some(stddev) = item.relative_speed_stddev {127 format!(" ± {}", format!("{stddev:5.2}").green())128 } else {25 unmodified linesmodified:src/export/markup.rs+1 added-1 removed
54 unmodified lines55 };56 let min_str = format_duration_value(measurement.min, Some(unit)).0;57 let max_str = format_duration_value(measurement.max, Some(unit)).0;58 let rel_str = format!("{:.2}", entry.relative_speed);59- let rel_stddev_str = if entry.is_fastest {59+ let rel_stddev_str = if entry.is_reference {60 "".into()61 } else if let Some(stddev) = entry.relative_speed_stddev {62 format!(" ± {stddev:.2}")63 } else {238 unmodified linesmodified:src/cli.rs+10 added
85 unmodified lines86 not every time as would happen with the --prepare option."87 ),88 )89 .arg(90+ Arg::new("reference")91+ .long("reference")92+ .action(ArgAction::Set)93+ .value_name("CMD")94+ .help(95+ "The reference command for the relative comparison of results. \96+ If this is unset, results are compared with the fastest command as reference."97+ )98+ )99+ .arg(100 Arg::new("prepare")101 .long("prepare")102 .short('p')103 .action(ArgAction::Append)293 unmodified linesmodified:src/options.rs+6 added
202 unmodified lines203 204 /// Whether or not to ignore non-zero exit codes205 pub command_failure_action: CmdFailureAction,206 207+ // Command to use as a reference for relative speed comparison208+ pub reference_command: Option<String>,209+210 /// Command(s) to run before each timing run211 pub preparation_command: Option<Vec<String>>,212 213 /// Command(s) to run after each timing run33 unmodified lines247 run_bounds: RunBounds::default(),248 warmup_count: 0,249 min_benchmarking_time: 3.0,250 command_failure_action: CmdFailureAction::RaiseError,251+ reference_command: None,252 preparation_command: None,253 conclusion_command: None,254 setup_command: None,255 cleanup_command: None,51 unmodified lines307 };308 309 options.setup_command = matches.get_one::<String>("setup").map(String::from);310 311+ options.reference_command = matches.get_one::<String>("reference").map(String::from);312+313 options.preparation_command = matches314 .get_many::<String>("prepare")315 .map(|values| values.map(String::from).collect::<Vec<String>>());316 188 unmodified lines