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.
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
Provenance
- Commit
29804c5- Tree
c064f0a- Author
Jason Peacock <jason@jasonpeacock.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
f1d4443
2 files changed+208 added−20 removed
modified:src/hyperfine/export/markdown.rs+133 added-16 removed
1 use super::Exporter;2+3+use hyperfine::format::{Unit, format_duration_value};4 use hyperfine::types::BenchmarkResult;5 6 use std::io::Result;7 6-const MULTIPLIER: f64 = 1e3;8+macro_rules! TABLE_HEADER {9+ ($unit:expr) => {10+ format!("| Command | Mean [{unit}] | Min…Max [{unit}] |\n|:---|---:|---:|\n", unit=$unit) };11+}12 13 #[derive(Default)]14 pub struct MarkdownExporter {}15 16 impl 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;20 21+ 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+ }25+26+ let mut destination = start_table(unit);27+28 for result in results {16- add_table_row(&mut destination, result);29+ add_table_row(&mut destination, result, unit);30 }31 32 Ok(destination)33 }34 }35 23-fn start_table() -> Vec<u8> {24- "| Command | Mean [ms] | Min…Max [ms] |\n|:---|---:|---:|\n"25- .bytes()26- .collect()36+fn start_table(unit: Unit) -> Vec<u8> {37+ TABLE_HEADER!(unit.short_name()).bytes().collect()38 }39+28-fn add_table_row(dest: &mut Vec<u8>, entry: &BenchmarkResult) {40+fn 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;45+46 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 }57+58+/// 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]65+fn test_markdown_format_ms() {66+ let exporter = MarkdownExporter::default();67+68+ let mut timing_results = vec![];69+70+ 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+ ));80+81+ 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+ ));91+92+ let formatted = String::from_utf8(exporter.serialize(&timing_results).unwrap()).unwrap();93+94+ 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"));99+100+ assert_eq!(formatted_expected, formatted);101+}102+103+/// This (again) demonstrates that the first entry's units (s) are used to set104+/// the units for all entries.105+#[test]106+fn test_markdown_format_s() {107+ let exporter = MarkdownExporter::default();108+109+ let mut timing_results = vec![];110+111+ 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+ ));121+122+ 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+ ));132+133+ let formatted = String::from_utf8(exporter.serialize(&timing_results).unwrap()).unwrap();134+135+ 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"));140+141+ assert_eq!(formatted_expected, formatted);142+}143+144+/// An empty list of benchmark results will only include the table header145+/// in the markdown output, using the default `Seconds` unit.146+#[test]147+fn test_markdown_format_empty_results() {148+ let exporter = MarkdownExporter::default();149+150+ let timing_results = vec![];151+152+ let formatted = String::from_utf8(exporter.serialize(&timing_results).unwrap()).unwrap();153+154+ let formatted_expected = TABLE_HEADER!("s");155+156+ assert_eq!(formatted_expected, formatted);157+}modified:src/hyperfine/format.rs+75 added-4 removed
4 unmodified lines5 Second,6 MilliSecond,7 }8 9+impl 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+ }17+18+ /// 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+ }27+28+ /// 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+}36+37 /// 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.39 pub fn format_duration(duration: Second, unit: Option<Unit>) -> String {40 match format_duration_unit(duration, unit) {2 unmodified lines43 }44 45 /// Like `format_duration`, but returns the target unit as well.46 pub 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);48+49+ (format!("{} {}", out_str, out_unit.short_name()), out_unit)50+}51+52+/// Like `format_duration`, but returns the target unit as well.53+pub fn format_duration_value(duration: Second, unit: Option<Unit>) -> (String, Unit) {54+55+ // Default to `Second` until proven otherwise.56+ let mut duration_unit = Unit::Second;57+58+ 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 }70+71+ (duration_unit.format(duration), duration_unit)72 }73 74 #[test]75+fn test_unit_short_name() {76+ assert_eq!("s", Unit::Second.short_name());77+ assert_eq!("ms", Unit::MilliSecond.short_name());78+}79+80+#[test]81+fn 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));84+85+ assert_eq!(0.001, Unit::Second.multiplier_from(Unit::MilliSecond));86+ assert_eq!(1000.0, Unit::MilliSecond.multiplier_from(Unit::Second));87+}88+89+// Note - the values are rounded when formatted.90+#[test]91+fn 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+}96+97+#[test]98 fn test_format_duration_unit_basic() {99 let (out_str, out_unit) = format_duration_unit(1.3, None);100 101 assert_eq!("1.300 s", out_str);35 unmodified lines