Skip to content
Myr

json.rs

This file

Path

src/export/json.rs

97 lines · 2.5 KiB · Rust

Last changed by

Export selected metrics side by side in CSVDavid Peterbefore adoption067ee70

History of this file

Take it

1use std::collections::BTreeMap;23use serde::Serialize;4use serde_json::to_vec_pretty;56use super::Exporter;7use crate::benchmark::benchmark_result::BenchmarkResult;8use crate::metric::{Metric, MetricSelection, Stats};910use anyhow::Result;1112mod metadata;13use metadata::Metadata;1415const JSON_SCHEMA_VERSION: u32 = 2;1617#[derive(Serialize)]18struct HyperfineSummary<'a> {19    schema_version: u32,20    metadata: &'a Metadata,21    primary_metric: &'static str,22    results: Vec<JsonBenchmarkResult<'a>>,23}2425#[derive(Serialize)]26struct JsonBenchmarkResult<'a> {27    #[serde(flatten)]28    result: &'a BenchmarkResult,29    summary: BTreeMap<&'static str, StatisticalSummary>,30}3132#[derive(Serialize)]33struct StatisticalSummary {34    #[serde(skip_serializing_if = "Option::is_none")]35    unit: Option<&'static str>,36    count: usize,37    mean: f64,38    stddev: Option<f64>,39    median: f64,40    min: f64,41    max: f64,42}4344impl StatisticalSummary {45    fn new(metric: Metric, stats: Stats) -> Self {46        Self {47            unit: match metric.base_unit().symbol {48                "s" => Some("second"),49                "B" => Some("byte"),50                _ => None,51            },52            count: stats.count,53            mean: stats.mean,54            stddev: stats.stddev,55            median: stats.median,56            min: stats.min,57            max: stats.max,58        }59    }60}6162#[derive(Default)]63pub struct JsonExporter {64    metadata: Metadata,65}6667impl Exporter for JsonExporter {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(),78            results: results79                .iter()80                .map(|result| JsonBenchmarkResult {81                    result,82                    summary: Metric::ALL83                        .iter()84                        .copied()85                        .filter_map(|metric| {86                            metric.summarize(&result.measurements).map(|stats| {87                                (metric.name(), StatisticalSummary::new(metric, stats))88                            })89                        })90                        .collect(),91                })92                .collect(),93        })?;94        output.push(b'\n');95        Ok(output)96    }97}