1use anyhow::{Context, Result};
14use serde::Serialize;
15use std::path::Path;
16
17#[derive(Debug, Serialize)]
18pub struct Export {
19 #[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 #[serde(serialize_with = "as_string")]
34 pub seed: u64,
35 pub runner: String,
37 pub time: String,
39 pub machine: crate::machine::Machine,
41}
42
43#[derive(Debug, Serialize)]
44pub struct ExportResult {
45 pub command: String,
48 pub bench: String,
49 pub subject: String,
50 #[serde(skip_serializing_if = "Option::is_none")]
54 pub version: Option<Option<String>>,
55 pub mean: f64,
57 pub stddev: Option<f64>,
59 pub median: f64,
60 pub min: f64,
61 pub max: f64,
62 pub times: Vec<f64>,
64 pub exit_codes: Vec<i32>,
69 #[serde(skip_serializing_if = "Option::is_none")]
71 pub checks: Option<Checks>,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
76pub struct Checks {
77 pub passed: usize,
78 pub total: usize,
79 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 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 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 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 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 #[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 #[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}