Skip to content
Myr

markdown.rs

This file

Path

src/export/markdown.rs

293 lines · 8.8 KiB · Rust

Last changed by

Move functionality to schedulerDavid Peterbefore adoptiondcfeede

History of this file

Take it

1use super::Exporter;2use crate::benchmark::benchmark_result::BenchmarkResult;3use crate::benchmark::relative_speed::{self, BenchmarkResultWithRelativeSpeed};4use crate::output::format::format_duration_value;5use crate::util::units::Unit;67use anyhow::{anyhow, Result};89#[derive(Default)]10pub struct MarkdownExporter {}1112impl Exporter for MarkdownExporter {13    fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>> {14        let unit = if let Some(unit) = unit {15            // Use the given unit for all entries.16            unit17        } else if let Some(first_result) = results.first() {18            // Use the first BenchmarkResult entry to determine the unit for all entries.19            format_duration_value(first_result.mean, None).120        } else {21            // Default to `Second`.22            Unit::Second23        };2425        if let Some(annotated_results) = relative_speed::compute(results) {26            let mut destination = start_table(unit);2728            for result in annotated_results {29                add_table_row(&mut destination, &result, unit);30            }3132            Ok(destination)33        } else {34            Err(anyhow!(35                "Relative speed comparison is not available for Markdown export."36            ))37        }38    }39}4041fn table_header(unit_short_name: String) -> String {42    format!(43        "| Command | Mean [{unit}] | Min [{unit}] | Max [{unit}] | Relative |\n|:---|---:|---:|---:|---:|\n",44        unit = unit_short_name45    )46}4748fn start_table(unit: Unit) -> Vec<u8> {49    table_header(unit.short_name()).bytes().collect()50}5152fn add_table_row(dest: &mut Vec<u8>, entry: &BenchmarkResultWithRelativeSpeed, unit: Unit) {53    let result = &entry.result;54    let mean_str = format_duration_value(result.mean, Some(unit)).0;55    let stddev_str = if let Some(stddev) = result.stddev {56        format!(" ± {}", format_duration_value(stddev, Some(unit)).0)57    } else {58        "".into()59    };60    let min_str = format_duration_value(result.min, Some(unit)).0;61    let max_str = format_duration_value(result.max, Some(unit)).0;62    let rel_str = format!("{:.2}", entry.relative_speed);63    let rel_stddev_str = if entry.is_fastest {64        "".into()65    } else if let Some(stddev) = entry.relative_speed_stddev {66        format!(" ± {:.2}", stddev)67    } else {68        "".into()69    };7071    dest.extend(72        format!(73            "| `{command}` | {mean}{stddev} | {min} | {max} | {rel}{rel_stddev} |\n",74            command = result.command.replace("|", "\\|"),75            mean = mean_str,76            stddev = stddev_str,77            min = min_str,78            max = max_str,79            rel = rel_str,80            rel_stddev = rel_stddev_str,81        )82        .as_bytes(),83    );84}8586/// Ensure the markdown output includes the table header and the multiple87/// benchmark results as a table. The list of actual times is not included88/// in the output.89///90/// This also demonstrates that the first entry's units (ms) are used to set91/// the units for all entries when the time unit is not given.92#[test]93fn test_markdown_format_ms() {94    use std::collections::BTreeMap;95    let exporter = MarkdownExporter::default();9697    let timing_results = vec![98        BenchmarkResult {99            command: String::from("sleep 0.1"),100            mean: 0.1057,101            stddev: Some(0.0016),102            median: 0.1057,103            user: 0.0009,104            system: 0.0011,105            min: 0.1023,106            max: 0.1080,107            times: Some(vec![0.1, 0.1, 0.1]),108            exit_codes: vec![Some(0), Some(0), Some(0)],109            parameters: BTreeMap::new(),110        },111        BenchmarkResult {112            command: String::from("sleep 2"),113            mean: 2.0050,114            stddev: Some(0.0020),115            median: 2.0050,116            user: 0.0009,117            system: 0.0012,118            min: 2.0020,119            max: 2.0080,120            times: Some(vec![2.0, 2.0, 2.0]),121            exit_codes: vec![Some(0), Some(0), Some(0)],122            parameters: BTreeMap::new(),123        },124    ];125126    let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();127128    let formatted_expected = format!(129        "{}\130| `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 |131| `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 |132",133        table_header("ms".to_string())134    );135136    assert_eq!(formatted_expected, formatted);137}138139/// This (again) demonstrates that the first entry's units (s) are used to set140/// the units for all entries when the time unit is not given.141#[test]142fn test_markdown_format_s() {143    use std::collections::BTreeMap;144    let exporter = MarkdownExporter::default();145146    let timing_results = vec![147        BenchmarkResult {148            command: String::from("sleep 2"),149            mean: 2.0050,150            stddev: Some(0.0020),151            median: 2.0050,152            user: 0.0009,153            system: 0.0012,154            min: 2.0020,155            max: 2.0080,156            times: Some(vec![2.0, 2.0, 2.0]),157            exit_codes: vec![Some(0), Some(0), Some(0)],158            parameters: BTreeMap::new(),159        },160        BenchmarkResult {161            command: String::from("sleep 0.1"),162            mean: 0.1057,163            stddev: Some(0.0016),164            median: 0.1057,165            user: 0.0009,166            system: 0.0011,167            min: 0.1023,168            max: 0.1080,169            times: Some(vec![0.1, 0.1, 0.1]),170            exit_codes: vec![Some(0), Some(0), Some(0)],171            parameters: BTreeMap::new(),172        },173    ];174175    let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();176177    let formatted_expected = format!(178        "{}\179| `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 |180| `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |181",182        table_header("s".to_string())183    );184185    assert_eq!(formatted_expected, formatted);186}187188/// The given time unit (s) is used to set the units for all entries.189#[test]190fn test_markdown_format_time_unit_s() {191    use std::collections::BTreeMap;192    let exporter = MarkdownExporter::default();193194    let timing_results = vec![195        BenchmarkResult {196            command: String::from("sleep 0.1"),197            mean: 0.1057,198            stddev: Some(0.0016),199            median: 0.1057,200            user: 0.0009,201            system: 0.0011,202            min: 0.1023,203            max: 0.1080,204            times: Some(vec![0.1, 0.1, 0.1]),205            exit_codes: vec![Some(0), Some(0), Some(0)],206            parameters: BTreeMap::new(),207        },208        BenchmarkResult {209            command: String::from("sleep 2"),210            mean: 2.0050,211            stddev: Some(0.0020),212            median: 2.0050,213            user: 0.0009,214            system: 0.0012,215            min: 2.0020,216            max: 2.0080,217            times: Some(vec![2.0, 2.0, 2.0]),218            exit_codes: vec![Some(0), Some(0), Some(0)],219            parameters: BTreeMap::new(),220        },221    ];222223    let formatted = String::from_utf8(224        exporter225            .serialize(&timing_results, Some(Unit::Second))226            .unwrap(),227    )228    .unwrap();229230    let formatted_expected = format!(231        "{}\232| `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |233| `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 |234",235        table_header("s".to_string())236    );237238    assert_eq!(formatted_expected, formatted);239}240241/// This (again) demonstrates that the given time unit (ms) is used to set242/// the units for all entries.243#[test]244fn test_markdown_format_time_unit_ms() {245    use std::collections::BTreeMap;246    let exporter = MarkdownExporter::default();247248    let timing_results = vec![249        BenchmarkResult {250            command: String::from("sleep 2"),251            mean: 2.0050,252            stddev: Some(0.0020),253            median: 2.0050,254            user: 0.0009,255            system: 0.0012,256            min: 2.0020,257            max: 2.0080,258            times: Some(vec![2.0, 2.0, 2.0]),259            exit_codes: vec![Some(0), Some(0), Some(0)],260            parameters: BTreeMap::new(),261        },262        BenchmarkResult {263            command: String::from("sleep 0.1"),264            mean: 0.1057,265            stddev: Some(0.0016),266            median: 0.1057,267            user: 0.0009,268            system: 0.0011,269            min: 0.1023,270            max: 0.1080,271            times: Some(vec![0.1, 0.1, 0.1]),272            exit_codes: vec![Some(0), Some(0), Some(0)],273            parameters: BTreeMap::new(),274        },275    ];276277    let formatted = String::from_utf8(278        exporter279            .serialize(&timing_results, Some(Unit::MilliSecond))280            .unwrap(),281    )282    .unwrap();283284    let formatted_expected = format!(285        "{}\286| `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 |287| `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 |288",289        table_header("ms".to_string())290    );291292    assert_eq!(formatted_expected, formatted);293}