Skip to content
Myr

Export selected metrics side by side in CSV

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

authored by David Peter · committed by David Peter · parent 25b0b54 · Browse files · 10 files+101 added−70 removed
This commit

State

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

Diff stats

10 files+101 added−70 removed

  • other:+101 added−70 removed

10 files+101 added−70 removed

modified:doc/hyperfine.1+6 added-4 removed
230 unmodified lines
231of the tool.232.HP233\fB\-\-metrics\fR \fIMETRIC[:UNIT],...|default|time|all\fP234.IP235Select the metrics to display, in order, with an optional unit for each.235Select the metrics to measure, in order, with an optional unit for each.236Default: \fBtime_wall_clock,memory_peak_resident\fR, or \fBtime_wall_clock\fR237on Windows, where peak resident memory is not yet supported.238.IP239Use \fBdefault\fR for the platform defaults, \fBtime\fR for
25 unmodified lines
265\fIFILE\fP. Use its selected unit, or choose a unit automatically when omitted.266.HP267\fB\-\-export\-csv\fR \fIFILE\fP268.IP269Export the primary metric's summary statistics as CSV to the given \fIFILE\fP,270identifying the metric and unit explicitly. Use the explicitly selected unit,271or the base unit (seconds, bytes, or unscaled counts) when omitted.269Export summary statistics for all selected metrics as CSV to the given \fIFILE\fP,270one row per command. Each metric contributes columns for unit, mean, stddev, median,271min, and max, prefixed with the metric name, in selection order. The command column272comes first and parameter columns come last. Use the explicitly selected units,273or base units (seconds, bytes, or unscaled counts) when omitted.274.HP275\fB\-\-export\-json\fR \fIFILE\fP276.IP277Export summary statistics and individual samples for all collected metrics as
117 unmodified lines
modified:src/benchmark/scheduler.rs+1 added-1 removed
67 unmodified lines
6869 assert_eq!(options.executor_kind, ExecutorKind::Mock(None));7071 let commands = Commands::from_cli_arguments(&cli_arguments)?;72 let export_manager = ExportManager::from_cli_arguments(&cli_arguments, options.metrics[0])?;72 let export_manager = ExportManager::from_cli_arguments(&cli_arguments, &options.metrics)?;7374 options.validate_against_command_list(&commands)?;7576 let mut scheduler = Scheduler::new(&commands, &options, &export_manager);
80 unmodified lines
modified:src/export/csv.rs+54 added-49 removed
2 unmodified lines
3use super::Exporter;4use crate::benchmark::benchmark_result::BenchmarkResult;5use crate::metric::MetricSelection;67use anyhow::{Context, Result};7use anyhow::Result;89#[derive(Default)]10pub struct CsvExporter {}1112impl Exporter for CsvExporter {13 fn serialize(&self, results: &[BenchmarkResult], primary: MetricSelection) -> Result<Vec<u8>> {14 // CSV never chooses units automatically: an omitted suffix means base units.15 let unit = primary.csv_unit();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![]);17 let mut headers: Vec<String> = [18 "command", "metric", "unit", "mean", "stddev", "median", "min", "max",19 ]20 .iter()21 .copied()22 .map(str::to_owned)23 .collect();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 .parameters
3 unmodified lines
42 }43 writer.write_record(headers)?;4445 for result in results {35 let stats = primary36 .metric37 .summarize(&result.measurements)38 .with_context(|| {39 format!(40 "Metric '{}' is unavailable for '{}'",41 primary.metric.name(),42 result.get_name()43 )44 })?;45 let mut fields = vec![46 result.get_name().to_owned(),47 primary.metric.name().to_owned(),48 unit.symbol.to_owned(),49 ];50 // Preserve numeric precision rather than using rounded display values.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(52 [53 Some(stats.mean),54 stats.stddev,55 Some(stats.median),56 Some(stats.min),57 Some(stats.max),58 ]59 .map(|value| {60 value61 .map(|value| (value / unit.scale).to_string())62 .unwrap_or_default()63 }),64 );65 fields.extend(69 result70 .parameters71 .values()72 .map(|parameter| parameter.value.clone()),
120 unmodified lines
193 ];194195 let actual = String::from_utf8(196 exporter194 .serialize(&results, MetricSelection::default())197 .serialize(198 &results,199 &MetricSelection::parse_list("time_wall_clock,memory_peak_resident").unwrap(),200 )201 .unwrap(),202 )203 .unwrap();204205 insta::assert_snapshot!(actual, @r#"200 command,metric,unit,mean,stddev,median,min,max,parameter_bar,parameter_foo201 command_a,time_wall_clock,s,9,2.6457513110645907,8,7,12,two,one202 command_b,time_wall_clock,s,18,1,18,17,19,seven,one206 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_foo207 command_a,s,9,2.6457513110645907,8,7,12,B,1024,0,1024,1024,1024,two,one208 command_b,s,18,1,18,17,19,B,1024,0,1024,1024,1024,seven,one209 "#);210211 for (selection, unit, mean) in [212 ("memory_peak_resident", "B", "1024"),213 ("memory_peak_resident:KiB", "KiB", "1"),214 ] {215 let output = exporter210 .serialize(&results, MetricSelection::parse_list(selection).unwrap()[0])216 .serialize(&results, &MetricSelection::parse_list(selection).unwrap())217 .unwrap();218 let mut reader = csv::Reader::from_reader(output.as_slice());219 let row = reader.records().next().unwrap().unwrap();214 assert_eq!(&row[1], "memory_peak_resident");215 assert_eq!(&row[2], unit);216 assert_eq!(&row[3], mean);220 assert_eq!(&row[1], unit);221 assert_eq!(&row[2], mean);222 }223}
modified:src/export/json.rs+6 added-1 removed
63 unmodified lines
64 metadata: Metadata,65}6667impl Exporter for JsonExporter {68 fn serialize(&self, results: &[BenchmarkResult], primary: MetricSelection) -> Result<Vec<u8>> {68 fn serialize(69 &self,70 results: &[BenchmarkResult],71 metrics: &[MetricSelection],72 ) -> Result<Vec<u8>> {73 let primary = metrics[0];74 let mut output = to_vec_pretty(&HyperfineSummary {75 schema_version: JSON_SCHEMA_VERSION,76 metadata: &self.metadata,77 primary_metric: primary.metric.name(),
20 unmodified lines
modified:src/export/markup.rs+6 added-1 removed
75 unmodified lines
76 fn command(&self, command: &str) -> String;77}7879impl<T: MarkupExporter> Exporter for T {80 fn serialize(&self, results: &[BenchmarkResult], primary: MetricSelection) -> Result<Vec<u8>> {80 fn serialize(81 &self,82 results: &[BenchmarkResult],83 metrics: &[MetricSelection],84 ) -> Result<Vec<u8>> {85 let primary = metrics[0];86 let stats: Vec<_> = results87 .iter()88 .map(|result| {89 primary
22 unmodified lines
modified:src/export/mod.rs+10 added-6 removed
42 unmodified lines
43}4445/// Interface for different exporters.46trait Exporter {47 /// Export the given entries in the serialized form.48 fn serialize(&self, results: &[BenchmarkResult], primary: MetricSelection) -> Result<Vec<u8>>;47 /// Export the given entries using a nonempty list of selected metrics, primary first.48 fn serialize(49 &self,50 results: &[BenchmarkResult],51 metrics: &[MetricSelection],52 ) -> Result<Vec<u8>>;53}5455pub enum ExportTarget {56 File(String),
7 unmodified lines
6465/// Handles the management of multiple file exporters.66pub struct ExportManager {67 exporters: Vec<ExporterWithTarget>,64 primary: MetricSelection,68 metrics: Vec<MetricSelection>,69}7071impl ExportManager {72 /// Build the ExportManager that will export the results specified73 /// in the given ArgMatches70 pub fn from_cli_arguments(matches: &ArgMatches, primary: MetricSelection) -> Result<Self> {74 pub fn from_cli_arguments(matches: &ArgMatches, metrics: &[MetricSelection]) -> Result<Self> {75 let mut export_manager = Self {76 exporters: vec![],73 primary,77 metrics: metrics.to_vec(),78 };79 {80 let mut add_exporter = |flag, exporttype| -> Result<()> {81 if let Some(filename) = matches.get_one::<String>(flag) {
41 unmodified lines
123 /// if a benchmark fails). In the latter case, we only print to stdout targets (in124 /// order not to clutter the output of hyperfine with intermediate results).125 pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> {126 for e in &self.exporters {123 let content = || e.exporter.serialize(results, self.primary);127 let content = || e.exporter.serialize(results, &self.metrics);128129 match e.target {130 ExportTarget::File(ref filename) => {131 if intermediate {
26 unmodified lines
modified:src/export/tests.rs+2 added-2 removed
13 unmodified lines
14 String::from_utf8(15 exporter16 .serialize(17 results,18 MetricSelection {18 &[MetricSelection {19 unit,20 ..MetricSelection::default()21 },21 }],22 )23 .unwrap(),24 )25 .unwrap()
445 unmodified lines
modified:src/cli.rs+4 added-3 removed
56 unmodified lines
57 .default_value("default")58 .hide_default_value(true)59 .help("Performance metrics to measure, in order.\n\n\60 This is either a preset name, or a comma-separated list of metrics with optional units. \61 The first metric is used for non-JSON exports, \61 CSV exports all selected metrics; markup exports use the first metric. \62 JSON always includes all collected metrics.\n\n\63 Presets (use one on its own):\n \64 default Wall-clock time and peak RSS\n \65 time Wall-clock, CPU, user, and system time\n \
236 unmodified lines
302 .long("export-csv")303 .action(ArgAction::Set)304 .value_name("FILE")305 .value_hint(ValueHint::FilePath)306 .help("Export the primary metric summary statistics as CSV to the given FILE. If you need \306 .help("Export summary statistics for all selected metrics as CSV to the given FILE. If you need \307 all metrics for each individual run, use the JSON export format. \308 Column names are prefixed with the metric name. \308 Use the explicitly selected unit, or the base unit when unspecified."),309 Use the explicitly selected units, or base units when unspecified."),310 )311 .arg(312 Arg::new("export-json")313 .long("export-json")
111 unmodified lines
modified:src/main.rs+1 added-1 removed
60 unmodified lines
61 }62 }63 }6465 let export_manager = ExportManager::from_cli_arguments(&cli_arguments, options.metrics[0])?;65 let export_manager = ExportManager::from_cli_arguments(&cli_arguments, &options.metrics)?;6667 let mut scheduler = Scheduler::new(&commands, &options, &export_manager);68 scheduler.run_benchmarks()?;69 scheduler.final_export()?;
25 unmodified lines
modified:README.md+11 added-2 removed
238 unmodified lines
239| `--metrics=all` | All available metrics |240241### Exporting results242243Hyperfine can export results to CSV, JSON, Markdown, AsciiDoc, and org-mode. Non-JSON formats244contain only the primary metric, which is the first metric selected by `--metrics`.243Hyperfine can export results to CSV, JSON, Markdown, AsciiDoc, and org-mode. CSV exports all244selected metrics, while Markdown, AsciiDoc, and org-mode contain only the primary metric,245which is the first metric selected by `--metrics`.246247#### Markdown248249You can use the `--export-markdown <file>` option to create tables like the following:
27 unmodified lines
277| ![](doc/histogram.png) | ![](doc/whisker.png) |278|---:|---:|279280281#### CSV282283Use `--export-csv <file>` to export one row per command. Each metric selected by `--metrics`284contributes a group of columns, in selection order: `<metric>_unit`, `<metric>_mean`,285`<metric>_stddev`, `<metric>_median`, `<metric>_min`, and `<metric>_max`.286287CSV uses explicitly selected units, or base units (seconds, bytes, or counts) when omitted.288289### Detailed benchmark flowchart290291The following chart explains the execution order of various benchmark runs when using options292like `--warmup`, `--prepare <cmd>`, `--setup <cmd>` or `--cleanup <cmd>`:
180 unmodified lines