Skip to content
Myr

Change markdown export to use seconds, closes #71

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

The markdown results exporter was using milliseconds, but the other results exporters are using the default seconds unit. Apply some refactoring so the same logic used to select units for the CLI output can be used to select the units for the markdown exporter. Now the units of the markdown exporter match that of the CLI. When there are multiple benchmarks, the CLI will choose the appropriate unit for each benchmark separately. In this case, the markdown exporter will use the first benchmark to select the units for all the results. *This will change the markdown results for all users from milliseconds to seconds, a UX breaking change.* Add unit tests for the markdown exporter to verify the output. Issue #80 proposes a new option to choose the units used for both the CLI report and results export.

authored by Jason Peacock · committed by David Peter · parent f1d4443 · Browse files · 2 files+208 added−20 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+208 added−20 removed

  • other:+208 added−20 removed

2 files+208 added−20 removed

modified:src/hyperfine/export/markdown.rs+133 added-16 removed
1use super::Exporter;23use hyperfine::format::{Unit, format_duration_value};4use hyperfine::types::BenchmarkResult;56use std::io::Result;76const MULTIPLIER: f64 = 1e3;8macro_rules! TABLE_HEADER {9 ($unit:expr) => {10 format!("| Command | Mean [{unit}] | Min…Max [{unit}] |\n|:---|---:|---:|\n", unit=$unit) };11}1213#[derive(Default)]14pub struct MarkdownExporter {}1516impl Exporter for MarkdownExporter {17 fn serialize(&self, results: &Vec<BenchmarkResult>) -> Result<Vec<u8>> {13 let mut destination = start_table();18 // Default to `Second`.19 let mut unit = Unit::Second;2021 if !results.is_empty() {22 // Use the first BenchmarkResult entry to determine the unit for all entries.23 unit = format_duration_value(results[0].mean, None).1;24 }2526 let mut destination = start_table(unit);2728 for result in results {16 add_table_row(&mut destination, result);29 add_table_row(&mut destination, result, unit);30 }3132 Ok(destination)33 }34}3523fn start_table() -> Vec<u8> {24 "| Command | Mean [ms] | Min…Max [ms] |\n|:---|---:|---:|\n"25 .bytes()26 .collect()36fn start_table(unit: Unit) -> Vec<u8> {37 TABLE_HEADER!(unit.short_name()).bytes().collect()38}3928fn add_table_row(dest: &mut Vec<u8>, entry: &BenchmarkResult) {40fn add_table_row(dest: &mut Vec<u8>, entry: &BenchmarkResult, unit: Unit) {41 let mean_str = format_duration_value(entry.mean, Some(unit)).0;42 let stddev_str = format_duration_value(entry.stddev, Some(unit)).0;43 let min_str = format_duration_value(entry.min, Some(unit)).0;44 let max_str = format_duration_value(entry.max, Some(unit)).0;4546 dest.extend(47 format!(31 "| `{}` | {:.1} ± {:.1} | {:.1}…{:.1} |\n",32 entry.command.replace("|", "\\|"),33 entry.mean * MULTIPLIER,34 entry.stddev * MULTIPLIER,35 entry.min * MULTIPLIER,36 entry.max * MULTIPLIER37 )38 .as_bytes(),48 "| `{command}` | {mean} ± {stddev} | {min}…{max} |\n",49 command=entry.command.replace("|", "\\|"),50 mean=mean_str,51 stddev=stddev_str,52 min=min_str,53 max=max_str,54 ).as_bytes(),55 );56}5758/// Ensure the markdown output includes the table header and the multiple59/// benchmark results as a table. The list of actual times is not included60/// in the output.61///62/// This also demonstrates that the first entry's units (ms) are used to set63/// the units for all entries.64#[test]65fn test_markdown_format_ms() {66 let exporter = MarkdownExporter::default();6768 let mut timing_results = vec![];6970 timing_results.push(BenchmarkResult::new(71 String::from("sleep 0.1"),72 0.1057, // mean73 0.0016, // std dev74 0.0009, // user_mean75 0.0011, // system_mean76 0.1023, // min77 0.1080, // max78 vec![0.1, 0.1, 0.1], // times79 ));8081 timing_results.push(BenchmarkResult::new(82 String::from("sleep 2"),83 2.0050, // mean84 0.0020, // std dev85 0.0009, // user_mean86 0.0012, // system_mean87 2.0020, // min88 2.0080, // max89 vec![2.0, 2.0, 2.0], // times90 ));9192 let formatted = String::from_utf8(exporter.serialize(&timing_results).unwrap()).unwrap();9394 let formatted_expected = format!(95"{}\96| `sleep 0.1` | 105.7 ± 1.6 | 102.3…108.0 |97| `sleep 2` | 2005.0 ± 2.0 | 2002.0…2008.0 |98", TABLE_HEADER!("ms"));99100 assert_eq!(formatted_expected, formatted);101}102103/// This (again) demonstrates that the first entry's units (s) are used to set104/// the units for all entries.105#[test]106fn test_markdown_format_s() {107 let exporter = MarkdownExporter::default();108109 let mut timing_results = vec![];110111 timing_results.push(BenchmarkResult::new(112 String::from("sleep 2"),113 2.0050, // mean114 0.0020, // std dev115 0.0009, // user_mean116 0.0012, // system_mean117 2.0020, // min118 2.0080, // max119 vec![2.0, 2.0, 2.0], // times120 ));121122 timing_results.push(BenchmarkResult::new(123 String::from("sleep 0.1"),124 0.1057, // mean125 0.0016, // std dev126 0.0009, // user_mean127 0.0011, // system_mean128 0.1023, // min129 0.1080, // max130 vec![0.1, 0.1, 0.1], // times131 ));132133 let formatted = String::from_utf8(exporter.serialize(&timing_results).unwrap()).unwrap();134135 let formatted_expected = format!(136"{}\137| `sleep 2` | 2.005 ± 0.002 | 2.002…2.008 |138| `sleep 0.1` | 0.106 ± 0.002 | 0.102…0.108 |139", TABLE_HEADER!("s"));140141 assert_eq!(formatted_expected, formatted);142}143144/// An empty list of benchmark results will only include the table header145/// in the markdown output, using the default `Seconds` unit.146#[test]147fn test_markdown_format_empty_results() {148 let exporter = MarkdownExporter::default();149150 let timing_results = vec![];151152 let formatted = String::from_utf8(exporter.serialize(&timing_results).unwrap()).unwrap();153154 let formatted_expected = TABLE_HEADER!("s");155156 assert_eq!(formatted_expected, formatted);157}
modified:src/hyperfine/format.rs+75 added-4 removed
4 unmodified lines
5 Second,6 MilliSecond,7}89impl Unit {10 /// The abbreviation of the Unit.11 pub fn short_name(&self) -> String {12 match *self {13 Unit::Second => String::from("s"),14 Unit::MilliSecond => String::from("ms"),15 }16 }1718 /// The multiplier value to convert from `from_unit` to the Unit.19 pub fn multiplier_from(&self, from_unit: Unit) -> f64 {20 match (*self, from_unit) {21 (Unit::Second, Unit::Second) => 1.0,22 (Unit::MilliSecond, Unit::MilliSecond) => 1.0,23 (Unit::Second, Unit::MilliSecond) => 1e-3,24 (Unit::MilliSecond, Unit::Second) => 1e3,25 }26 }2728 /// Returns the Second value formatted for the Unit.29 pub fn format(&self, value: Second) -> String {30 match *self {31 Unit::Second => format!("{:.3}", value * self.multiplier_from(Unit::Second)),32 Unit::MilliSecond => format!("{:.1}", value * self.multiplier_from(Unit::Second)),33 }34 }35}3637/// Format the given duration as a string. The output-unit can be enforced by setting `unit` to38/// `Some(target_unit)`. If `unit` is `None`, it will be determined automatically.39pub fn format_duration(duration: Second, unit: Option<Unit>) -> String {40 match format_duration_unit(duration, unit) {
2 unmodified lines
43}4445/// Like `format_duration`, but returns the target unit as well.46pub fn format_duration_unit(duration: Second, unit: Option<Unit>) -> (String, Unit) {19 if (duration < 1.0 && unit.is_none()) || unit == Some(Unit::MilliSecond) {20 (format!("{:.1} ms", duration * 1e3), Unit::MilliSecond)21 } else {22 (format!("{:.3} s", duration), Unit::Second)47 let (out_str, out_unit) = format_duration_value(duration, unit);4849 (format!("{} {}", out_str, out_unit.short_name()), out_unit)50}5152/// Like `format_duration`, but returns the target unit as well.53pub fn format_duration_value(duration: Second, unit: Option<Unit>) -> (String, Unit) {5455 // Default to `Second` until proven otherwise.56 let mut duration_unit = Unit::Second;5758 match unit {59 Some(unit_option) => {60 // Use user-supplied unit.61 duration_unit = unit_option;62 },63 None => {64 if duration < 1.0 {65 // It's a small value, use `Millisecond` instead.66 duration_unit = Unit::MilliSecond;67 }68 },69 }7071 (duration_unit.format(duration), duration_unit)72}7374#[test]75fn test_unit_short_name() {76 assert_eq!("s", Unit::Second.short_name());77 assert_eq!("ms", Unit::MilliSecond.short_name());78}7980#[test]81fn test_unit_multiplier_from() {82 assert_eq!(1.0, Unit::Second.multiplier_from(Unit::Second));83 assert_eq!(1.0, Unit::MilliSecond.multiplier_from(Unit::MilliSecond));8485 assert_eq!(0.001, Unit::Second.multiplier_from(Unit::MilliSecond));86 assert_eq!(1000.0, Unit::MilliSecond.multiplier_from(Unit::Second));87}8889// Note - the values are rounded when formatted.90#[test]91fn test_unit_format() {92 let value: Second = 123.456789;93 assert_eq!("123.457", Unit::Second.format(value));94 assert_eq!("123456.8", Unit::MilliSecond.format(value));95}9697#[test]98fn test_format_duration_unit_basic() {99 let (out_str, out_unit) = format_duration_unit(1.3, None);100101 assert_eq!("1.300 s", out_str);
35 unmodified lines