Skip to content
Myr

Fix nan/inf output for very fast commands

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

closes #319

authored by sharkdp · committed by David Peter · parent 314e4e3 · Browse files · 4 files+103 added−61 removed
This commit

State

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

Diff stats

4 files+103 added−61 removed

  • other:+103 added−61 removed

4 files+103 added−61 removed

modified:src/hyperfine/export/markdown.rs+12 added-7 removed
3 unmodified lines
4use crate::hyperfine::internal::{compute_relative_speed, BenchmarkResultWithRelativeSpeed};5use crate::hyperfine::types::BenchmarkResult;6use crate::hyperfine::units::Unit;78use std::io::Result;8use std::io::{Error, ErrorKind, Result};910#[derive(Default)]11pub struct MarkdownExporter {}12
9 unmodified lines
22 // Default to `Second`.23 Unit::Second24 };2526 let annotated_results = compute_relative_speed(results);26 if let Some(annotated_results) = compute_relative_speed(results) {27 let mut destination = start_table(unit);2828 let mut destination = start_table(unit);29 for result in annotated_results {30 add_table_row(&mut destination, &result, unit);31 }3230 for result in annotated_results {31 add_table_row(&mut destination, &result, unit);33 Ok(destination)34 } else {35 Err(Error::new(36 ErrorKind::Other,37 "Relative speed comparison is not available for Markdown export.",38 ))39 }3334 Ok(destination)40 }41}4243fn table_header(unit_short_name: String) -> String {
242 unmodified lines
modified:src/hyperfine/internal.rs+66 added-35 removed
50 unmodified lines
51 .min_by(|a, b| a.partial_cmp(b).unwrap())52 .unwrap()53}5455#[derive(Debug)]56pub struct BenchmarkResultWithRelativeSpeed<'a> {57 pub result: &'a BenchmarkResult,58 pub relative_speed: Scalar,59 pub relative_speed_stddev: Scalar,
5 unmodified lines
65}6667pub fn compute_relative_speed<'a>(68 results: &'a [BenchmarkResult],68) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> {69) -> Option<Vec<BenchmarkResultWithRelativeSpeed<'a>>> {70 let fastest: &BenchmarkResult = results71 .iter()72 .min_by(|&l, &r| compare_mean_time(l, r))73 .expect("at least one benchmark result");7474 results75 .iter()76 .map(|result| {77 let ratio = result.mean / fastest.mean;75 if fastest.mean == 0.0 {76 return None;77 }7879 Some(80 results81 .iter()82 .map(|result| {83 let ratio = result.mean / fastest.mean;8479 // https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas80 // Covariance asssumed to be 0, i.e. variables are assumed to be independent81 let ratio_stddev = ratio82 * ((result.stddev / result.mean).powi(2) + (fastest.stddev / fastest.mean).powi(2))85 // https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas86 // Covariance asssumed to be 0, i.e. variables are assumed to be independent87 let ratio_stddev = ratio88 * ((result.stddev / result.mean).powi(2)89 + (fastest.stddev / fastest.mean).powi(2))90 .sqrt();9185 BenchmarkResultWithRelativeSpeed {86 result,87 relative_speed: ratio,88 relative_speed_stddev: ratio_stddev,89 is_fastest: result == fastest,90 }91 })92 .collect()92 BenchmarkResultWithRelativeSpeed {93 result,94 relative_speed: ratio,95 relative_speed_stddev: ratio_stddev,96 is_fastest: result == fastest,97 }98 })99 .collect(),100 )101}102103pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {104 if results.len() < 2 {105 return;106 }107100 let mut annotated_results = compute_relative_speed(&results);101 annotated_results.sort_by(|l, r| compare_mean_time(l.result, r.result));108 if let Some(mut annotated_results) = compute_relative_speed(&results) {109 annotated_results.sort_by(|l, r| compare_mean_time(l.result, r.result));110103 let fastest = &annotated_results[0];104 let others = &annotated_results[1..];111 let fastest = &annotated_results[0];112 let others = &annotated_results[1..];113106 println!("{}", "Summary".bold());107 println!(" '{}' ran", fastest.result.command.cyan());114 println!("{}", "Summary".bold());115 println!(" '{}' ran", fastest.result.command.cyan());116109 for item in others {110 println!(111 "{} ± {} times faster than '{}'",112 format!("{:8.2}", item.relative_speed).bold().green(),113 format!("{:.2}", item.relative_speed_stddev).green(),114 &item.result.command.magenta()117 for item in others {118 println!(119 "{} ± {} times faster than '{}'",120 format!("{:8.2}", item.relative_speed).bold().green(),121 format!("{:.2}", item.relative_speed_stddev).green(),122 &item.result.command.magenta()123 );124 }125 } else {126 eprintln!(127 "{}: The benchmark comparison could not be computed as some benchmark times are zero. \128 This could be caused by background interference during the initial calibration phase \129 of hyperfine, in combination with very fast commands (faster than a few milliseconds). \130 Try to re-run the benchmark on a quiet system. If it does not help, you command is \131 most likely too fast to be accurately benchmarked by hyperfine.",132 "Note".bold().red()133 );134 }135}136
5 unmodified lines
142 assert_eq!(1.0, max(&[-1.0, 1.0]));143 assert_eq!(1.0, max(&[-1.0, 1.0, 0.0]));144}145128#[test]129fn test_compute_relative_speed() {130 use approx::assert_relative_eq;146#[cfg(test)]147fn create_result(name: &str, mean: Scalar) -> BenchmarkResult {148 use std::collections::BTreeMap;149133 let create_result = |name: &str, mean| BenchmarkResult {150 BenchmarkResult {151 command: name.into(),152 mean,153 stddev: 1.0,154 median: mean,
2 unmodified lines
157 min: mean,158 max: mean,159 times: None,160 parameters: BTreeMap::new(),144 };161 }162}163164#[test]165fn test_compute_relative_speed() {166 use approx::assert_relative_eq;167168 let results = vec![169 create_result("cmd1", 3.0),170 create_result("cmd2", 2.0),171 create_result("cmd3", 5.0),172 ];173152 let annotated_results = compute_relative_speed(&results);174 let annotated_results = compute_relative_speed(&results).unwrap();175176 assert_relative_eq!(1.5, annotated_results[0].relative_speed);177 assert_relative_eq!(1.0, annotated_results[1].relative_speed);178 assert_relative_eq!(2.5, annotated_results[2].relative_speed);179}180181#[test]182fn test_compute_relative_speed_for_zero_times() {183 let results = vec![create_result("cmd1", 1.0), create_result("cmd2", 0.0)];184185 let annotated_results = compute_relative_speed(&results);186187 assert!(annotated_results.is_none());188}189190pub fn tokenize<'a>(values: &'a str) -> Vec<String> {191 let mut tokens = vec![];192 let mut buf = String::new();193
56 unmodified lines
modified:src/main.rs+23 added-19 removed
14 unmodified lines
15use crate::hyperfine::export::{ExportManager, ExportType};16use crate::hyperfine::internal::{tokenize, write_benchmark_comparison};17use crate::hyperfine::parameter_range::get_parameterized_commands;18use crate::hyperfine::types::{19 BenchmarkResult, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption, ParameterValue,19 CmdFailureAction, Command, HyperfineOptions, OutputStyleOption, ParameterValue,20};21use crate::hyperfine::units::Unit;2223/// Print error message to stderr and terminate
2 unmodified lines
26 std::process::exit(1);27}2829/// Runs the benchmark for the given commands30fn run(commands: &[Command<'_>], options: &HyperfineOptions) -> io::Result<Vec<BenchmarkResult>> {30fn run(31 commands: &[Command<'_>],32 options: &HyperfineOptions,33 export_manager: &ExportManager,34) -> io::Result<()> {35 let shell_spawning_time =36 mean_shell_spawning_time(&options.shell, options.output_style, options.show_output)?;3738 let mut timing_results = vec![];
11 unmodified lines
50 for (num, cmd) in commands.iter().enumerate() {51 timing_results.push(run_benchmark(num, cmd, shell_spawning_time, options)?);52 }5350 Ok(timing_results)54 // Print relative speed comparison55 if options.output_style != OutputStyleOption::Disabled {56 write_benchmark_comparison(&timing_results);57 }5859 // Export results60 let ans = export_manager.write_results(timing_results, options.time_unit);61 if let Err(e) = ans {62 error(&format!(63 "The following error occurred while exporting: {}",64 e65 ));66 }6768 Ok(())69}7071fn main() {72 let matches = get_arg_matches(env::args_os());
1 unmodified line
74 let export_manager = build_export_manager(&matches);75 let commands = build_commands(&matches);7677 let res = match options {60 Ok(ref opts) => run(&commands, &opts),78 Ok(ref opts) => run(&commands, &opts, &export_manager),79 Err(ref e) => error(&e.to_string()),80 };8182 match res {65 Ok(timing_results) => {66 let options = options.unwrap();6768 if options.output_style != OutputStyleOption::Disabled {69 write_benchmark_comparison(&timing_results);70 }7172 let ans = export_manager.write_results(timing_results, options.time_unit);73 if let Err(e) = ans {74 error(&format!(75 "The following error occurred while exporting: {}",76 e77 ));78 }79 }83 Ok(_) => {}84 Err(e) => error(&e.to_string()),85 }86}87
248 unmodified lines
modified:CHANGELOG.md+2 added
22 unmodified lines
2324## Bugfixes2526- Fix a bug in the outlier detection which would only detect "slow outliers" but not the fast ones (runs that are much faster than the rest of the benchmarking runs), see #32927- Better error messages for very fast commands that would lead to inf/nan results in the relative28 speed comparison, see #31929- Keep output colorized when the output is not interactive and `--style=full` or `--style=color` is used.3031## Other32## Packaging
208 unmodified lines