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. Everything tak adds is an extra key, and none of
10//! hyperfine's changes meaning: `checks` is present only for a subject with a
11//! `check`, and `version` only for one with a `version_cmd`.
12
13use anyhow::{Context, Result};
14use serde::Serialize;
15use std::path::Path;
16
17#[derive(Debug, Serialize)]
18pub struct Export {
19    /// How the run was made, so a surprising result can be traced and its
20    /// sample order repeated. Extra top-level keys; hyperfine has none.
21    #[serde(flatten)]
22    pub meta: Meta,
23    pub results: Vec<ExportResult>,
24}
25
26#[derive(Debug, Clone, Serialize)]
27pub struct Meta {
28    pub tak_version: String,
29    /// The run's seed: `tak run --seed` with it repeats the sample order, as
30    /// long as `runs = "auto"` settles on the same counts. A string, because
31    /// a seed given with `--seed` can exceed 2^53, and a JSON number that
32    /// large is rounded by JavaScript and jq — silently naming another order.
33    #[serde(serialize_with = "as_string")]
34    pub seed: u64,
35    /// The runner class the run would be recorded under.
36    pub runner: String,
37    /// When the run finished, RFC 3339.
38    pub time: String,
39    /// What the run was measured on, for a results page to state.
40    pub machine: crate::machine::Machine,
41}
42
43#[derive(Debug, Serialize)]
44pub struct ExportResult {
45    /// hyperfine's display name: the subject, or the benchmark for a
46    /// single-command one.
47    pub command: String,
48    pub bench: String,
49    pub subject: String,
50    /// What the subject's `version_cmd` printed. Absent when it has none,
51    /// `null` when it failed — a subject is still measured and exported
52    /// without its version.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub version: Option<Option<String>>,
55    /// Seconds, like hyperfine, not the milliseconds tak records.
56    pub mean: f64,
57    /// `null` for a single sample, as hyperfine writes it.
58    pub stddev: Option<f64>,
59    pub median: f64,
60    pub min: f64,
61    pub max: f64,
62    /// Every timed sample in seconds, in the order taken.
63    pub times: Vec<f64>,
64    /// What each sample exited with, aligned with `times`. Always one of the
65    /// subject's `ok_exit_codes` (0 unless it says otherwise): a sample that
66    /// exits with anything else drops its subject rather than being kept. A
67    /// failed `check` is not a failed run, and is reported in `checks`.
68    pub exit_codes: Vec<i32>,
69    /// The outcome of the subject's `check`, when it has one.
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub checks: Option<Checks>,
72}
73
74/// How a subject's timed samples fared against its `check`.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
76pub struct Checks {
77    pub passed: usize,
78    pub total: usize,
79    /// Whether each sample passed, aligned with `times`, so a failure can be
80    /// matched to the time it produced.
81    pub samples: Vec<bool>,
82}
83
84impl Checks {
85    pub fn new(samples: &[bool]) -> Self {
86        Checks {
87            passed: samples.iter().filter(|&&ok| ok).count(),
88            total: samples.len(),
89            samples: samples.to_vec(),
90        }
91    }
92}
93
94impl ExportResult {
95    /// A result whose samples all exited 0; see [`Self::with_exit_codes`].
96    pub fn new(bench: &str, subject: &str, command: &str, samples_ms: &[f64]) -> Self {
97        let times: Vec<f64> = samples_ms.iter().map(|ms| ms / 1000.0).collect();
98        let mut sorted = times.clone();
99        sorted.sort_by(f64::total_cmp);
100        let n = sorted.len();
101        let mean = sorted.iter().sum::<f64>() / n as f64;
102        let stddev = (n > 1).then(|| {
103            (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
104        });
105        // The true median, as hyperfine reports it, rather than tak's p50
106        // (the upper middle sample).
107        let median = if n.is_multiple_of(2) {
108            (sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
109        } else {
110            sorted[n / 2]
111        };
112        ExportResult {
113            command: command.to_string(),
114            bench: bench.to_string(),
115            subject: subject.to_string(),
116            version: None,
117            mean,
118            stddev,
119            median,
120            min: sorted[0],
121            max: sorted[n - 1],
122            exit_codes: vec![0; n],
123            times,
124            checks: None,
125        }
126    }
127
128    /// Record what each sample actually exited with, one per sample.
129    pub fn with_exit_codes(mut self, codes: &[i32]) -> Self {
130        debug_assert_eq!(codes.len(), self.times.len());
131        self.exit_codes = codes.to_vec();
132        self
133    }
134
135    /// Attach a subject's check outcomes, one per sample.
136    pub fn with_checks(mut self, samples: &[bool]) -> Self {
137        debug_assert_eq!(samples.len(), self.times.len());
138        self.checks = Some(Checks::new(samples));
139        self
140    }
141}
142
143fn as_string<S: serde::Serializer>(v: &u64, s: S) -> Result<S::Ok, S::Error> {
144    s.serialize_str(&v.to_string())
145}
146
147pub fn write(path: &Path, meta: Meta, results: Vec<ExportResult>) -> Result<()> {
148    let json = serde_json::to_string_pretty(&Export { meta, results })?;
149    std::fs::write(path, json + "\n").with_context(|| format!("could not write {}", path.display()))
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn times_are_seconds_and_the_median_is_the_true_median() {
158        let r = ExportResult::new("b", "s", "s", &[4000.0, 1000.0, 3000.0, 2000.0]);
159        assert_eq!(r.times, [4.0, 1.0, 3.0, 2.0], "kept in the order taken");
160        assert_eq!((r.min, r.max, r.mean, r.median), (1.0, 4.0, 2.5, 2.5));
161        assert_eq!(r.exit_codes, [0; 4]);
162        assert!(r.stddev.unwrap() > 0.0);
163    }
164
165    /// `checks` is absent without a check, so a subject that has none
166    /// exports exactly the hyperfine shape it did before.
167    #[test]
168    fn checks_are_exported_only_when_there_are_some() {
169        let plain = serde_json::to_value(ExportResult::new("b", "s", "s", &[1.0, 2.0])).unwrap();
170        assert!(plain.get("checks").is_none(), "{plain}");
171
172        let checked = serde_json::to_value(
173            ExportResult::new("b", "s", "s", &[1.0, 2.0, 3.0]).with_checks(&[true, false, true]),
174        )
175        .unwrap();
176        assert_eq!(
177            checked["checks"],
178            serde_json::json!({"passed": 2, "total": 3, "samples": [true, false, true]})
179        );
180        assert_eq!(checked["exit_codes"], serde_json::json!([0, 0, 0]));
181    }
182
183    #[test]
184    fn a_version_is_absent_unless_asked_for_and_null_when_it_failed() {
185        let mut r = ExportResult::new("b", "s", "s", &[5.0]);
186        let json = serde_json::to_value(&r).unwrap();
187        assert!(json.get("version").is_none());
188        r.version = Some(None);
189        assert!(serde_json::to_value(&r).unwrap()["version"].is_null());
190        r.version = Some(Some("tool 1.2.3".into()));
191        assert_eq!(serde_json::to_value(&r).unwrap()["version"], "tool 1.2.3");
192    }
193
194    #[test]
195    fn a_single_sample_has_no_stddev() {
196        let r = ExportResult::new("b", "s", "s", &[5.0]);
197        assert_eq!(r.stddev, None);
198        let json = serde_json::to_value(&r).unwrap();
199        assert!(json["stddev"].is_null());
200    }
201
202    /// Each sample's real exit code is kept, in the order taken, rather than
203    /// assumed to be 0.
204    #[test]
205    fn exit_codes_are_what_each_sample_exited_with() {
206        let r = ExportResult::new("b", "s", "s", &[1.0, 2.0]).with_exit_codes(&[1, 0]);
207        assert_eq!(r.exit_codes, [1, 0]);
208    }
209}