Skip to content
Myr

csv.rs

This file

Path

src/export/csv.rs

225 lines · 8.5 KiB · Rust

Last changed by

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

History of this file

Take it

1use csv::WriterBuilder;23use super::Exporter;4use crate::benchmark::benchmark_result::BenchmarkResult;5use crate::metric::MetricSelection;67use anyhow::Result;89#[derive(Default)]10pub struct CsvExporter {}1112impl Exporter for CsvExporter {13    fn serialize(14        &self,15        results: &[BenchmarkResult],16        metrics: &[MetricSelection],17    ) -> Result<Vec<u8>> {18        // Omit metrics unavailable for all commands (possible with `--metrics all`).19        let metrics: Vec<_> = metrics20            .iter()21            .filter(|selection| {22                results23                    .iter()24                    .any(|result| selection.metric.summarize(&result.measurements).is_some())25            })26            .collect();27        let mut writer = WriterBuilder::new().from_writer(vec![]);28        let mut headers = vec!["command".to_owned()];29        for selection in &metrics {30            headers.extend(31                ["unit", "mean", "stddev", "median", "min", "max"]32                    .map(|field| format!("{}_{field}", selection.metric.name())),33            );34        }35        if let Some(result) = results.first() {36            headers.extend(37                result38                    .parameters39                    .keys()40                    .map(|name| format!("parameter_{name}")),41            );42        }43        writer.write_record(headers)?;4445        for result in results {46            let mut fields = vec![result.get_name().to_owned()];47            for selection in &metrics {48                // CSV never chooses units automatically: an omitted suffix means base units.49                let unit = selection.csv_unit();50                let stats = selection.metric.summarize(&result.measurements);51                fields.push(unit.symbol.to_owned());52                // Preserve numeric precision rather than using rounded display values.53                fields.extend(54                    [55                        stats.map(|stats| stats.mean),56                        stats.and_then(|stats| stats.stddev),57                        stats.map(|stats| stats.median),58                        stats.map(|stats| stats.min),59                        stats.map(|stats| stats.max),60                    ]61                    .map(|value| {62                        value63                            .map(|value| (value / unit.scale).to_string())64                            .unwrap_or_default()65                    }),66                );67            }68            fields.extend(69                result70                    .parameters71                    .values()72                    .map(|parameter| parameter.value.clone()),73            );74            writer.write_record(fields)?;75        }7677        Ok(writer.into_inner()?)78    }79}8081#[test]82fn test_csv() {83    use crate::benchmark::benchmark_result::Parameter;84    use crate::benchmark::measurement::{Measurement, Measurements};85    use crate::quantity::{byte, second, Information, Time, Zero};8687    use std::collections::BTreeMap;88    use std::process::ExitStatus;8990    let exporter = CsvExporter::default();9192    let results = vec![93        BenchmarkResult {94            environment: BTreeMap::new(),95            command: String::from("echo command_a"),96            name: Some(String::from("command_a")),97            display_name: String::from("command_a"),98            measurements: Measurements::new(vec![99                Measurement {100                    time_wall_clock: Time::new::<second>(7.0),101                    time_cpu: Time::new::<second>(7.0),102                    time_user: Time::new::<second>(7.0),103                    time_system: Time::zero(),104                    memory_peak_resident: Some(Information::new::<byte>(1024.)),105                    hardware_counters: Default::default(),106                    exit_status: ExitStatus::default(),107                },108                Measurement {109                    time_wall_clock: Time::new::<second>(8.0),110                    time_cpu: Time::new::<second>(8.0),111                    time_user: Time::new::<second>(8.0),112                    time_system: Time::zero(),113                    memory_peak_resident: Some(Information::new::<byte>(1024.)),114                    hardware_counters: Default::default(),115                    exit_status: ExitStatus::default(),116                },117                Measurement {118                    time_wall_clock: Time::new::<second>(12.0),119                    time_cpu: Time::new::<second>(12.0),120                    time_user: Time::new::<second>(12.0),121                    time_system: Time::zero(),122                    memory_peak_resident: Some(Information::new::<byte>(1024.)),123                    hardware_counters: Default::default(),124                    exit_status: ExitStatus::default(),125                },126            ]),127            parameters: {128                let mut params = BTreeMap::new();129                params.insert(130                    "foo".into(),131                    Parameter {132                        value: "one".into(),133                    },134                );135                params.insert(136                    "bar".into(),137                    Parameter {138                        value: "two".into(),139                    },140                );141                params142            },143        },144        BenchmarkResult {145            environment: BTreeMap::new(),146            command: String::from("command_b"),147            name: None,148            display_name: String::from("command_b"),149            measurements: Measurements::new(vec![150                Measurement {151                    time_wall_clock: Time::new::<second>(17.0),152                    time_cpu: Time::new::<second>(17.0),153                    time_user: Time::new::<second>(17.0),154                    time_system: Time::zero(),155                    memory_peak_resident: Some(Information::new::<byte>(1024.)),156                    hardware_counters: Default::default(),157                    exit_status: ExitStatus::default(),158                },159                Measurement {160                    time_wall_clock: Time::new::<second>(18.0),161                    time_cpu: Time::new::<second>(18.0),162                    time_user: Time::new::<second>(18.0),163                    time_system: Time::zero(),164                    memory_peak_resident: Some(Information::new::<byte>(1024.)),165                    hardware_counters: Default::default(),166                    exit_status: ExitStatus::default(),167                },168                Measurement {169                    time_wall_clock: Time::new::<second>(19.0),170                    time_cpu: Time::new::<second>(19.0),171                    time_user: Time::new::<second>(19.0),172                    time_system: Time::zero(),173                    memory_peak_resident: Some(Information::new::<byte>(1024.)),174                    hardware_counters: Default::default(),175                    exit_status: ExitStatus::default(),176                },177            ]),178            parameters: {179                let mut params = BTreeMap::new();180                params.insert(181                    "foo".into(),182                    Parameter {183                        value: "one".into(),184                    },185                );186                params.insert(187                    "bar".into(),188                    Parameter {189                        value: "seven".into(),190                    },191                );192                params193            },194        },195    ];196197    let actual = String::from_utf8(198        exporter199            .serialize(200                &results,201                &MetricSelection::parse_list("time_wall_clock,memory_peak_resident").unwrap(),202            )203            .unwrap(),204    )205    .unwrap();206207    insta::assert_snapshot!(actual, @r#"208    command,time_wall_clock_unit,time_wall_clock_mean,time_wall_clock_stddev,time_wall_clock_median,time_wall_clock_min,time_wall_clock_max,memory_peak_resident_unit,memory_peak_resident_mean,memory_peak_resident_stddev,memory_peak_resident_median,memory_peak_resident_min,memory_peak_resident_max,parameter_bar,parameter_foo209    command_a,s,9,2.6457513110645907,8,7,12,B,1024,0,1024,1024,1024,two,one210    command_b,s,18,1,18,17,19,B,1024,0,1024,1024,1024,seven,one211    "#);212213    for (selection, unit, mean) in [214        ("memory_peak_resident", "B", "1024"),215        ("memory_peak_resident:KiB", "KiB", "1"),216    ] {217        let output = exporter218            .serialize(&results, &MetricSelection::parse_list(selection).unwrap())219            .unwrap();220        let mut reader = csv::Reader::from_reader(output.as_slice());221        let row = reader.records().next().unwrap().unwrap();222        assert_eq!(&row[1], unit);223        assert_eq!(&row[2], mean);224    }225}