Refine JSON schema and command metadata
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Peter · committed by David Peter · parent c5d3a81 · Browse files · 15 files·+59 added−60 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+59 added−60 removed
- tests:+8 added−7 removed
- other:+51 added−53 removed
Provenance
- Commit
0d86e78- Tree
dc94efe- Author
David Peter <mail@david-peter.de>- Committer
David Peter <mail@david-peter.de>- Parent
c5d3a81
15 files changed+59 added−60 removed
modified:scripts/advanced_statistics.py+1 added-1 removed
59 unmodified lines60 p95 = np.percentile(ts, 95)61 62 iqr = p75 - p2563 64- print(f"Command '{result['command']}'")64+ print(f"Command '{result.get('name', result['command'])}'")65 print(f" runs: {summary['count']:8d}")66 print(f" mean: {summary['mean'] * unit.factor():8.3f} {unit_str}")67 if summary["stddev"] is None:68 print(f" stddev: {'N/A':>8}")12 unmodified linesmodified:scripts/plot_benchmark_comparison.py+1 added-1 removed
42 unmodified lines43 44 for i, filename in enumerate(args.files):45 with open(filename) as f:46 results = json.load(f)["results"]47- benchmark_commands = [b["command"] for b in results]47+ benchmark_commands = [b.get("name", b["command"]) for b in results]48 if commands is None:49 commands = benchmark_commands50 else:51 assert (32 unmodified linesmodified:scripts/plot_histogram.py+1 added-1 removed
64 unmodified lines65 66 if args.labels:67 labels = args.labels.split(",")68 else:69- labels = [b["command"] for b in results]69+ labels = [b.get("name", b["command"]) for b in results]70 all_times = [71 [m["time_wall_clock"]["value"] for m in b["measurements"]] for b in results72 ]73 34 unmodified linesmodified:scripts/plot_progression.py+2 added-2 removed
50 unmodified lines51 with open(args.file) as f:52 results = json.load(f)["results"]53 54 for result in results:55- label = result["command"]55+ label = result.get("name", result["command"])56 times = [m["time_wall_clock"]["value"] for m in result["measurements"]]57 num = len(times)58 nums = range(num)59 15 unmodified lines75 plt.title(args.title)76 77 legend = []78 for result in results:79- legend.append(result["command"])79+ legend.append(result.get("name", result["command"]))80 if not args.no_moving_average:81 legend.append("moving average")82 plt.legend(legend)83 6 unmodified linesmodified:scripts/plot_whisker.py+1 added-1 removed
35 unmodified lines36 37 if args.labels:38 labels = args.labels.split(",")39 else:40- labels = [b["command"] for b in results]40+ labels = [b.get("name", b["command"]) for b in results]41 times = [[m["time_wall_clock"]["value"] for m in b["measurements"]] for b in results]42 43 if args.sort_by == "median":44 medians = [b["summary"]["time_wall_clock"]["median"] for b in results]22 unmodified linesmodified:scripts/welch_ttest.py+1 added-1 removed
24 unmodified lines25 if len(results) != 2:26 print("The input file has to contain exactly two benchmarks")27 sys.exit(1)28 29-a, b = (x["command"] for x in results[:2])29+a, b = (x.get("name", x["command"]) for x in results[:2])30 X, Y = ([m["time_wall_clock"]["value"] for m in x["measurements"]] for x in results[:2])31 32 print(f"Command 1: {a}")33 print(f"Command 2: {b}\n")15 unmodified linesmodified:src/benchmark/benchmark_result.rs+10 added-5 removed
7 unmodified lines8 /// Parameter value and whether it was used in the command line template9 #[derive(Debug, Default, Clone, Serialize, PartialEq)]10 pub struct Parameter {11 pub value: String,12+ #[serde(skip_serializing)]13 pub is_unused: bool,14 }15 16 /// Meta data and performance metrics for a single benchmark17 #[derive(Debug, Default, Clone, Serialize, PartialEq)]18 pub struct BenchmarkResult {18- /// The display name of the command being benchmarked19+ /// The expanded command line being benchmarked20 pub command: String,21 21- /// The expanded command line, when it differs from the display name22+ /// The display name, when it differs from the command line23 #[serde(skip_serializing_if = "Option::is_none")]23- pub command_raw: Option<String>,24+ pub name: Option<String>,25 26 /// Performance metric measurements and exit codes for each run27 #[serde(flatten)]28 pub measurements: Measurements,3 unmodified lines32 pub parameters: BTreeMap<String, Parameter>,33 }34 35 impl BenchmarkResult {36+ pub fn get_name(&self) -> &str {37+ self.name.as_deref().unwrap_or(&self.command)38+ }39+40 /// The average wall clock time41 pub fn mean_wall_clock_time(&self) -> Time {42 self.measurements.time_wall_clock_mean()43 }44 40- /// The full command line of the program that is being benchmarked, possibly including a list of45+ /// The display name of the command, possibly including a list of46 /// parameters that were not used in the command line template.47 pub fn command_with_unused_parameters(&self) -> String {48 let parameters = self49 .parameters8 unmodified lines58 } else {59 format!(" ({parameters})")60 };61 57- format!("{}{}", self.command, parameters)62+ format!("{}{}", self.get_name(), parameters)63 }64 }modified:src/benchmark/mod.rs+4 added-4 removed
473 unmodified lines474 }475 476 self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;477 478- let command = self.command.get_name();479- let command_raw = self.command.get_command_line();480- let command_raw = (command_raw != command).then_some(command_raw);478+ let command = self.command.get_command_line();479+ let name = self.command.get_name();480+ let name = (name != command).then_some(name);481 482 Ok(BenchmarkResult {483 command,484- command_raw,484+ name,485 measurements,486 parameters: self487 .command488 .get_parameters()14 unmodified linesmodified:src/benchmark/relative_speed.rs+1 added-1 removed
156 unmodified lines157 use crate::quantity::second;158 159 BenchmarkResult {160 command: name.into(),161- command_raw: None,161+ name: None,162 measurements: Measurements {163 measurements: vec![Measurement {164 time_wall_clock: Time::new::<second>(mean),165 time_user: Time::new::<second>(mean),71 unmodified linesmodified:src/export/json/metadata.rs-4 removed
1 use serde::Serialize;2 3-pub(super) const JSON_SCHEMA_VERSION: u32 = 2;4-3 #[derive(Debug, Serialize)]4 pub(super) struct Metadata {7- json_schema_version: u32,5 hyperfine_version: &'static str,6 #[serde(skip_serializing_if = "Option::is_none")]7 pub start_time: Option<String>,8 pub platform: Platform,1 unmodified line10 11 impl Default for Metadata {12 fn default() -> Self {13 Self {17- json_schema_version: JSON_SCHEMA_VERSION,14 hyperfine_version: env!("CARGO_PKG_VERSION"),15 start_time: utc_now(),16 platform: Platform::detect(),17 }42 unmodified linesmodified:src/export/csv.rs+4 added-4 removed
40 unmodified lines41 writer.write_record(headers)?;42 }43 44 for res in results {45- let mut fields = vec![Cow::Borrowed(res.command.as_bytes())];45+ let mut fields = vec![Cow::Borrowed(res.get_name().as_bytes())];46 for f in &[47 res.mean_wall_clock_time(),48 res.measurements.stddev().unwrap_or_default(),49 res.measurements.median(),29 unmodified lines79 let exporter = CsvExporter::default();80 81 let results = vec![82 BenchmarkResult {83- command: String::from("command_a"),84- command_raw: None,83+ command: String::from("echo command_a"),84+ name: Some(String::from("command_a")),85 measurements: Measurements::new(vec![86 Measurement {87 time_wall_clock: Time::new::<second>(7.0),88 time_user: Time::new::<second>(7.0),36 unmodified lines125 },126 },127 BenchmarkResult {128 command: String::from("command_b"),129- command_raw: None,129+ name: None,130 measurements: Measurements::new(vec![131 Measurement {132 time_wall_clock: Time::new::<second>(17.0),133 time_user: Time::new::<second>(17.0),53 unmodified linesmodified:src/export/json.rs+10 added-6 removed
13 unmodified lines14 15 mod metadata;16 use metadata::Metadata;17 18+const JSON_SCHEMA_VERSION: u32 = 2;19+20 #[derive(Serialize)]21 struct HyperfineSummary<'a> {22+ schema_version: u32,23 metadata: &'a Metadata,24 results: Vec<JsonBenchmarkResult<'a>>,25 }26 91 unmodified lines118 _sort_order: SortOrder,119 _reference_index: Option<usize>,120 ) -> Result<Vec<u8>> {121 let mut output = to_vec_pretty(&HyperfineSummary {122+ schema_version: JSON_SCHEMA_VERSION,123 metadata: &self.metadata,124 results: results125 .iter()126 .map(|result| JsonBenchmarkResult {58 unmodified lines185 ),186 ] {187 let result = BenchmarkResult {188 command: "example".into(),185- command_raw: None,189+ name: None,190 measurements: Measurements::new(vec![Measurement {191 peak_memory_usage: memory,192 ..Measurement::default()193 }]),5 unmodified lines199 .serialize(&[result], None, SortOrder::Command, None)200 .unwrap();201 let actual: serde_json::Value = serde_json::from_slice(&output).unwrap();202 let mut expected = json!({203+ "schema_version": JSON_SCHEMA_VERSION,204 "metadata": {200- "json_schema_version": metadata::JSON_SCHEMA_VERSION,205 "hyperfine_version": env!("CARGO_PKG_VERSION"),206 "start_time": "2000-02-29T12:34:56Z",207 "platform": exporter.metadata.platform208 },44 unmodified lines253 let results: Vec<_> = vec![("small", vec![1.0, 3.0]), ("large", vec![10.0])]254 .into_iter()255 .map(|(size, times)| BenchmarkResult {256 command: "example".into(),253- command_raw: None,257+ name: None,258 parameters: [(259 "size".into(),260 Parameter {261 value: size.into(),258- is_unused: true,262+ is_unused: size == "small",263 },264 )]265 .into(),266 measurements: Measurements::new(12 unmodified lines279 .unwrap();280 let actual: serde_json::Value = serde_json::from_slice(&output).unwrap();281 let results = actual["results"].as_array().unwrap();282 assert_eq!(results.len(), 2);279- assert_eq!(results[0]["parameters"]["size"]["value"], "small");280- assert_eq!(results[1]["parameters"]["size"]["value"], "large");283+ assert_eq!(results[0]["parameters"]["size"], json!({"value": "small"}));284+ assert_eq!(results[1]["parameters"]["size"], json!({"value": "large"}));285 assert_eq!(results[0]["measurements"].as_array().unwrap().len(), 2);286 assert_eq!(results[1]["measurements"].as_array().unwrap().len(), 1);287 assert_eq!(288 results[0]["summary"]["time_wall_clock"],56 unmodified linesmodified:src/export/tests.rs+8 added-8 removed
26 unmodified lines27 fn test_markup_export_auto_ms() {28 let results = [29 BenchmarkResult {30 command: String::from("sleep 0.1"),31- command_raw: None,31+ name: None,32 measurements: Measurements::new(vec![33 Measurement {34 time_wall_clock: Time::new::<second>(0.09),35 time_user: Time::new::<second>(0.09),19 unmodified lines55 parameters: BTreeMap::new(),56 },57 BenchmarkResult {58 command: String::from("sleep 2"),59- command_raw: None,59+ name: None,60 measurements: Measurements::new(vec![61 Measurement {62 time_wall_clock: Time::new::<second>(2.0),63 time_user: Time::new::<second>(2.0),64 unmodified lines128 fn test_markup_export_auto_s() {129 let results = [130 BenchmarkResult {131 command: String::from("sleep 2"),132- command_raw: None,132+ name: None,133 measurements: Measurements::new(vec![134 Measurement {135 time_wall_clock: Time::new::<second>(2.1),136 time_user: Time::new::<second>(2.1),19 unmodified lines156 parameters: BTreeMap::new(),157 },158 BenchmarkResult {159 command: String::from("sleep 0.1"),160- command_raw: None,160+ name: None,161 measurements: Measurements::new(vec![162 Measurement {163 time_wall_clock: Time::new::<second>(0.1),164 time_user: Time::new::<second>(0.1),64 unmodified lines229 fn test_markup_export_manual_ms() {230 let timing_results = [231 BenchmarkResult {232 command: String::from("sleep 2"),233- command_raw: None,233+ name: None,234 measurements: Measurements::new(vec![235 Measurement {236 time_wall_clock: Time::new::<second>(2.1),237 time_user: Time::new::<second>(2.1),19 unmodified lines257 parameters: BTreeMap::new(),258 },259 BenchmarkResult {260 command: String::from("sleep 0.1"),261- command_raw: None,261+ name: None,262 measurements: Measurements::new(vec![263 Measurement {264 time_wall_clock: Time::new::<second>(0.1),265 time_user: Time::new::<second>(0.1),63 unmodified lines329 fn test_markup_export_manual_s() {330 let results = [331 BenchmarkResult {332 command: String::from("sleep 2"),333- command_raw: None,333+ name: None,334 measurements: Measurements::new(vec![335 Measurement {336 time_wall_clock: Time::new::<second>(2.01),337 time_user: Time::new::<second>(2.01),19 unmodified lines357 parameters: BTreeMap::new(),358 },359 BenchmarkResult {360 command: String::from("sleep 0.1"),361- command_raw: None,361+ name: None,362 measurements: Measurements::new(vec![363 Measurement {364 time_wall_clock: Time::new::<second>(0.11),365 time_user: Time::new::<second>(0.11),60 unmodified linesmodified:tests/integration_tests.rs+8 added-7 removed
41 unmodified lines42 .success();43 }44 45 #[test]46-fn json_includes_raw_command_only_when_different() {46+fn json_includes_name_only_when_different() {47 for (args, expected) in [48 (vec!["sleep 0.01"], vec![("sleep 0.01", None)]),49 (50 vec!["--command-name=example", "sleep 0.01"],51- vec![("example", Some("sleep 0.01"))],51+ vec![("sleep 0.01", Some("example"))],52 ),53 (54 vec!["--command-name=sleep 0.01", "sleep 0.01"],55 vec![("sleep 0.01", None)],6 unmodified lines62 "--command-name=delay {delay}",63 "sleep {delay}",64 ],65 vec![66- ("delay 0.01", Some("sleep 0.01")),67- ("delay 0.02", Some("sleep 0.02")),66+ ("sleep 0.01", Some("delay 0.01")),67+ ("sleep 0.02", Some("delay 0.02")),68 ],69 ),70 (71 vec![14 unmodified lines86 assert!(output.status.success());87 let export: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();88 let results = export["results"].as_array().unwrap();89 assert_eq!(results.len(), expected.len());90- for (result, (command, command_raw)) in results.iter().zip(expected) {90+ for (result, (command, name)) in results.iter().zip(expected) {91 assert_eq!(result["command"], command);92+ assert!(result.get("command_raw").is_none());93 assert_eq!(93- result.get("command_raw"),94- command_raw.map(serde_json::Value::from).as_ref()94+ result.get("name"),95+ name.map(serde_json::Value::from).as_ref()96 );97 }98 }99 }1256 unmodified linesmodified:README.md+7 added-14 removed
156 unmodified lines157 | `fd -HI '.*[0-9]\.jpg$'` | 0.232 ± 0.002 | 0.230 | 0.236 | 1.00 |158 159 #### JSON160 161-The JSON export contains a top-level `"schema_version": 2` and a `results` array with one entry162-per benchmark. Earlier exports without `schema_version` use the legacy format (version 1).163-The schema version is independent of the hyperfine release version and changes when the format164-changes incompatibly; adding optional metrics does not require a new schema version.161+The JSON export includes the following metrics for each measured run (excluding warmup runs):162 166-Each result has a `measurements` array with one object per measured run (excluding warmup runs):167-168-| Field | Format | Meaning and platform differences |163+| Metric | Unit | Meaning and platform differences |164 |:---|:---|:---|170-| `time_wall_clock` | `{ "value": number, "unit": "second" }` | Elapsed time, including time spent waiting or descheduled. Available on all platforms. |171-| `time_user` | `{ "value": number, "unit": "second" }` | CPU time spent in user mode, accumulated across threads. On Unix, includes descendants whose usage propagates through parents waiting for them. On Windows, includes processes associated with the benchmark's job object. |172-| `time_system` | `{ "value": number, "unit": "second" }` | CPU time spent in kernel mode, with the same process accounting as `time_user`. |173-| `peak_memory_usage` | `{ "value": number, "unit": "byte" }` | Peak resident set size (RSS) on Linux and macOS; omitted on Windows. This is the largest per-process peak among the command and descendants whose usage is collected by waiting for them, **not the simultaneous total memory of the process tree**. Linux's KiB counter and macOS's byte counter are both exported in bytes. On macOS, this is RSS, not Apple's separate memory-footprint metric. |174-| `exit_code` | Integer or `null` | Process exit code; `0` indicates success. On Unix, termination by a signal is encoded as `128 + signal number`. `null` means no exit code could be determined. Failed runs are included when allowed by `--ignore-failure`. |165+| `time_wall_clock` | second | Elapsed time, including time spent waiting or descheduled. Available on all platforms. |166+| `time_user` | second | CPU time spent in user mode, accumulated across threads. On Unix, includes descendants whose usage propagates through parents waiting for them. On Windows, includes processes associated with the benchmark's job object. |167+| `time_system` | second | CPU time spent in kernel mode, with the same process accounting as `time_user`. |168+| `peak_memory_usage` | byte | Peak resident set size (RSS) on Linux and macOS; omitted on Windows. This is the largest per-process peak among the command and descendants whose usage is collected by waiting for them, **not the simultaneous total memory of the process tree**. Linux's KiB counter and macOS's byte counter are both exported in bytes. On macOS, this is RSS, not Apple's separate memory-footprint metric. |169 176-Metrics unavailable on a platform are omitted, rather than reported as zero. Consumers should177-accept missing metrics and additional fields as new metrics are introduced. Time values are always170+Metrics unavailable on a platform are omitted, rather than reported as zero. Time values are always171 exported in seconds, regardless of `--time-unit`. When using a shell, the estimated shell startup172 CPU and wall-clock times are subtracted; memory usage is not adjusted.173 174 For example, two concurrent worker processes that each use 128 MiB can produce a197 unmodified lines