1use anyhow::{Context, Result};
12use serde::Serialize;
13use std::path::Path;
14
15#[derive(Debug, Serialize)]
16pub struct Export {
17 pub results: Vec<ExportResult>,
18}
19
20#[derive(Debug, Serialize)]
21pub struct ExportResult {
22 pub command: String,
25 pub bench: String,
26 pub subject: String,
27 pub mean: f64,
29 pub stddev: Option<f64>,
31 pub median: f64,
32 pub min: f64,
33 pub max: f64,
34 pub times: Vec<f64>,
36 pub exit_codes: Vec<i32>,
39}
40
41impl ExportResult {
42 pub fn new(bench: &str, subject: &str, command: &str, samples_ms: &[f64]) -> Self {
43 let times: Vec<f64> = samples_ms.iter().map(|ms| ms / 1000.0).collect();
44 let mut sorted = times.clone();
45 sorted.sort_by(f64::total_cmp);
46 let n = sorted.len();
47 let mean = sorted.iter().sum::<f64>() / n as f64;
48 let stddev = (n > 1).then(|| {
49 (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
50 });
51 let median = if n.is_multiple_of(2) {
54 (sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
55 } else {
56 sorted[n / 2]
57 };
58 ExportResult {
59 command: command.to_string(),
60 bench: bench.to_string(),
61 subject: subject.to_string(),
62 mean,
63 stddev,
64 median,
65 min: sorted[0],
66 max: sorted[n - 1],
67 exit_codes: vec![0; n],
68 times,
69 }
70 }
71}
72
73pub fn write(path: &Path, results: Vec<ExportResult>) -> Result<()> {
74 let json = serde_json::to_string_pretty(&Export { results })?;
75 std::fs::write(path, json + "\n").with_context(|| format!("could not write {}", path.display()))
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81
82 #[test]
83 fn times_are_seconds_and_the_median_is_the_true_median() {
84 let r = ExportResult::new("b", "s", "s", &[4000.0, 1000.0, 3000.0, 2000.0]);
85 assert_eq!(r.times, [4.0, 1.0, 3.0, 2.0], "kept in the order taken");
86 assert_eq!((r.min, r.max, r.mean, r.median), (1.0, 4.0, 2.5, 2.5));
87 assert_eq!(r.exit_codes, [0; 4]);
88 assert!(r.stddev.unwrap() > 0.0);
89 }
90
91 #[test]
92 fn a_single_sample_has_no_stddev() {
93 let r = ExportResult::new("b", "s", "s", &[5.0]);
94 assert_eq!(r.stddev, None);
95 let json = serde_json::to_value(&r).unwrap();
96 assert!(json["stddev"].is_null());
97 }
98}