Skip to main content

tak_cli/
export.rs

1//! Results in hyperfine's `--export-json` shape.
2//!
3//! Projects moving from hyperfine already have scripts that read that file
4//! (aube's `generate-results.js` reads `mean`, `stddev`, `min` and `max`).
5//! Writing the same shape lets them switch the measuring tool without
6//! rewriting what consumes it. `bench` and `subject` are extra keys, which
7//! hyperfine consumers ignore; they are what tell entries apart once one file
8//! holds several benchmarks. `user` and `system` are omitted because tak does
9//! not measure CPU time.
10
11use 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    /// hyperfine's display name: the subject, or the benchmark for a
23    /// single-command one.
24    pub command: String,
25    pub bench: String,
26    pub subject: String,
27    /// Seconds, like hyperfine, not the milliseconds tak records.
28    pub mean: f64,
29    /// `null` for a single sample, as hyperfine writes it.
30    pub stddev: Option<f64>,
31    pub median: f64,
32    pub min: f64,
33    pub max: f64,
34    /// Every timed sample in seconds, in the order taken.
35    pub times: Vec<f64>,
36    /// Always zero: a sample that fails drops its subject rather than being
37    /// kept, so every exported time is from a successful run.
38    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        // The true median, as hyperfine reports it, rather than tak's p50
52        // (the upper middle sample).
53        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}