Skip to content
Myr

csv.rs

This file

Path

src/export/csv.rs

184 lines · 6.5 KiB · Rust

Last changed by

Merge pull request #969 from sharkdp/codex/result-measurementsDavid Peterbefore adoptione689520

History of this file

Take it

1use std::borrow::Cow;23use csv::WriterBuilder;45use super::Exporter;6use crate::benchmark::benchmark_result::BenchmarkResult;7use crate::options::SortOrder;8use crate::quantity::{second, TimeUnit};910use anyhow::Result;1112#[derive(Default)]13pub struct CsvExporter {}1415impl Exporter for CsvExporter {16    fn serialize(17        &self,18        results: &[BenchmarkResult],19        _unit: Option<TimeUnit>,20        _sort_order: SortOrder,21    ) -> Result<Vec<u8>> {22        const CSV_PRECISION: usize = 6;2324        let mut writer = WriterBuilder::new().from_writer(vec![]);2526        {27            let mut headers: Vec<Cow<[u8]>> = [28                // The list of times and exit codes cannot be exported to the CSV file - omit them.29                "command", "mean", "stddev", "median", "user", "system", "min", "max",30            ]31            .iter()32            .map(|x| Cow::Borrowed(x.as_bytes()))33            .collect();34            if let Some(res) = results.first() {35                for param_name in res.parameters.keys() {36                    headers.push(Cow::Owned(format!("parameter_{param_name}").into_bytes()));37                }38            }39            writer.write_record(headers)?;40        }4142        for res in results {43            let mut fields = vec![Cow::Borrowed(res.command.as_bytes())];44            for f in &[45                res.mean_wall_clock_time().get::<second>(),46                res.measurements47                    .stddev()48                    .unwrap_or_default()49                    .get::<second>(),50                res.measurements.median().get::<second>(),51                res.measurements.time_user_mean().get::<second>(),52                res.measurements.time_system_mean().get::<second>(),53                res.measurements.min().get::<second>(),54                res.measurements.max().get::<second>(),55            ] {56                fields.push(Cow::Owned(format!("{f:.CSV_PRECISION$}").into_bytes()))57            }58            for v in res.parameters.values() {59                fields.push(Cow::Borrowed(v.value.as_bytes()))60            }61            writer.write_record(fields)?;62        }6364        Ok(writer.into_inner()?)65    }66}6768#[test]69fn test_csv() {70    use crate::benchmark::benchmark_result::Parameter;71    use crate::benchmark::measurement::{Measurement, Measurements};72    use crate::quantity::{byte, second, Information, Time, Zero};7374    use std::collections::BTreeMap;75    use std::process::ExitStatus;7677    let exporter = CsvExporter::default();7879    let results = vec![80        BenchmarkResult {81            command: String::from("command_a"),82            command_with_unused_parameters: String::from("command_a"),83            measurements: Measurements::new(vec![84                Measurement {85                    time_wall_clock: Time::new::<second>(7.0),86                    time_user: Time::new::<second>(7.0),87                    time_system: Time::zero(),88                    peak_memory_usage: Information::new::<byte>(1024.),89                    exit_status: ExitStatus::default(),90                },91                Measurement {92                    time_wall_clock: Time::new::<second>(8.0),93                    time_user: Time::new::<second>(8.0),94                    time_system: Time::zero(),95                    peak_memory_usage: Information::new::<byte>(1024.),96                    exit_status: ExitStatus::default(),97                },98                Measurement {99                    time_wall_clock: Time::new::<second>(12.0),100                    time_user: Time::new::<second>(12.0),101                    time_system: Time::zero(),102                    peak_memory_usage: Information::new::<byte>(1024.),103                    exit_status: ExitStatus::default(),104                },105            ]),106            parameters: {107                let mut params = BTreeMap::new();108                params.insert(109                    "foo".into(),110                    Parameter {111                        value: "one".into(),112                        is_unused: false,113                    },114                );115                params.insert(116                    "bar".into(),117                    Parameter {118                        value: "two".into(),119                        is_unused: false,120                    },121                );122                params123            },124        },125        BenchmarkResult {126            command: String::from("command_b"),127            command_with_unused_parameters: String::from("command_b"),128            measurements: Measurements::new(vec![129                Measurement {130                    time_wall_clock: Time::new::<second>(17.0),131                    time_user: Time::new::<second>(17.0),132                    time_system: Time::zero(),133                    peak_memory_usage: Information::new::<byte>(1024.),134                    exit_status: ExitStatus::default(),135                },136                Measurement {137                    time_wall_clock: Time::new::<second>(18.0),138                    time_user: Time::new::<second>(18.0),139                    time_system: Time::zero(),140                    peak_memory_usage: Information::new::<byte>(1024.),141                    exit_status: ExitStatus::default(),142                },143                Measurement {144                    time_wall_clock: Time::new::<second>(19.0),145                    time_user: Time::new::<second>(19.0),146                    time_system: Time::zero(),147                    peak_memory_usage: Information::new::<byte>(1024.),148                    exit_status: ExitStatus::default(),149                },150            ]),151            parameters: {152                let mut params = BTreeMap::new();153                params.insert(154                    "foo".into(),155                    Parameter {156                        value: "one".into(),157                        is_unused: false,158                    },159                );160                params.insert(161                    "bar".into(),162                    Parameter {163                        value: "seven".into(),164                        is_unused: false,165                    },166                );167                params168            },169        },170    ];171172    let actual = String::from_utf8(173        exporter174            .serialize(&results, Some(TimeUnit::Second), SortOrder::Command)175            .unwrap(),176    )177    .unwrap();178179    insta::assert_snapshot!(actual, @r#"180    command,mean,stddev,median,user,system,min,max,parameter_bar,parameter_foo181    command_a,9.000000,2.645751,8.000000,9.000000,0.000000,7.000000,12.000000,two,one182    command_b,18.000000,1.000000,18.000000,18.000000,0.000000,17.000000,19.000000,seven,one183    "#);184}