Merge pull request #790 from sharkdp/new-metrics
Before adoption: this commit came in with the history the project adopted, so no landing records it.
New JSON format
authored by David Peter · committed by GitHub · parents ad6b4e2, 3cf3c5d · Browse files · 30 files·+1156 added−298 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
30 files+1156 added−298 removed
- tests:+558 added−1 removed
- other:+598 added−297 removed
Provenance
- Commit
f26c015- Tree
8282c16- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
ad6b4e2- Parent 2
3cf3c5d
30 files changed+1156 added−298 removed
modified:scripts/advanced_statistics.py+13 added-12 removed
48 unmodified lines49 50 with open(args.file) as f:51 results = json.load(f)["results"]52 53-commands = [b["command"] for b in results]54-times = [b["times"] for b in results]53+for result in results:54+ summary = result["summary"]["time_wall_clock"]55+ ts = [m["time_wall_clock"]["value"] * unit.factor() for m in result["measurements"]]56 56-for command, ts in zip(commands, times):57- ts = [t * unit.factor() for t in ts]58-57 p05 = np.percentile(ts, 5)58 p25 = np.percentile(ts, 25)59 p75 = np.percentile(ts, 75)60 p95 = np.percentile(ts, 95)61 62 iqr = p75 - p2563 66- print(f"Command '{command}'")67- print(f" runs: {len(ts):8d}")68- print(f" mean: {np.mean(ts):8.3f} {unit_str}")69- print(f" stddev: {np.std(ts, ddof=1):8.3f} {unit_str}")70- print(f" median: {np.median(ts):8.3f} {unit_str}")71- print(f" min: {np.min(ts):8.3f} {unit_str}")72- print(f" max: {np.max(ts):8.3f} {unit_str}")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}")69+ else:70+ print(f" stddev: {summary['stddev'] * unit.factor():8.3f} {unit_str}")71+ print(f" median: {summary['median'] * unit.factor():8.3f} {unit_str}")72+ print(f" min: {summary['min'] * unit.factor():8.3f} {unit_str}")73+ print(f" max: {summary['max'] * unit.factor():8.3f} {unit_str}")74 print()75 print(" percentiles:")76 print(f" P_05 .. P_95: {p05:.3f} {unit_str} .. {p95:.3f} {unit_str}")77 print(3 unmodified linesmodified:scripts/plot_benchmark_comparison.py+2 added-2 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 (52 commands == benchmark_commands53 ), f"Unexpected commands in {filename}: {benchmark_commands}, expected: {commands}"54- data.append([round(b["mean"], 2) for b in results])54+ data.append([b["summary"]["time_wall_clock"]["mean"] for b in results])55 if args.benchmark_names:56 inputs.append(args.benchmark_names[i])57 else:58 inputs.append(filename.stem)25 unmodified linesmodified:scripts/plot_histogram.py+4 added-2 removed
64 unmodified lines65 66 if args.labels:67 labels = args.labels.split(",")68 else:69- labels = [b["command"] for b in results]70-all_times = [b["times"] 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 74 t_min = float(args.t_min) if args.t_min else np.min(list(map(np.min, all_times)))75 t_max = float(args.t_max) if args.t_max else np.max(list(map(np.max, all_times)))76 31 unmodified linesmodified:scripts/plot_parametrized.py+6 added-3 removed
69 unmodified lines70 die(71 f"benchmarks must have exactly one parameter, but found multiple: {sorted(params_dict)}"72 )73 [(name, value)] = params_dict.items()74- return (name, float(value))74+ return (name, float(value["value"]))75 76 77 parameter_name = None78 7 unmodified lines86 f"files must all have the same parameter name, but found {parameter_name!r} vs. {this_parameter_name!r}"87 )88 parameter_name = this_parameter_name89 90- times_mean = [b["mean"] for b in results]91- times_stddev = [b["stddev"] for b in results]90+ summaries = [b["summary"]["time_wall_clock"] for b in results]91+ times_mean = [s["mean"] for s in summaries]92+ times_stddev = [93+ s["stddev"] if s["stddev"] is not None else float("nan") for s in summaries94+ ]95 96 plt.errorbar(x=parameter_values, y=times_mean, yerr=times_stddev, capsize=2)97 98 plt.xlabel(parameter_name)17 unmodified linesmodified:scripts/plot_progression.py+6 added-4 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"]56- times = result["times"]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 60 plt.scatter(x=nums, y=times, marker=".")1 unmodified line62 plt.xlim([-1, num])63 64 if not args.no_moving_average:65 moving_average_width = (66- num // 5 if args.moving_average_width is None else args.moving_average_width66+ max(1, num // 5)67+ if args.moving_average_width is None68+ else args.moving_average_width69 )70 71 average = moving_average(times, moving_average_width)72 plt.plot(nums, average, "-")2 unmodified lines75 plt.title(args.title)76 77 legend = []78 for result in results:77- 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+3 added-3 removed
35 unmodified lines36 37 if args.labels:38 labels = args.labels.split(",")39 else:40- labels = [b["command"] for b in results]41-times = [b["times"] 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["median"] for b in results]44+ medians = [b["summary"]["time_wall_clock"]["median"] for b in results]45 indices = sorted(range(len(labels)), key=lambda k: medians[k])46 labels = [labels[i] for i in indices]47 times = [times[i] for i in indices]48 18 unmodified linesmodified:scripts/welch_ttest.py+2 added-2 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])30-X, Y = (x["times"] 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")34 14 unmodified linesmodified:src/benchmark/benchmark_result.rs+28 added-70 removed
1 use std::collections::BTreeMap;2 3-use serde::ser::SerializeStruct;4-use serde::{Serialize, Serializer};3+use serde::Serialize;4 5 use crate::benchmark::measurement::Measurements;7-use crate::quantity::{byte, second, Time};8-use crate::util::exit_code::extract_exit_code;6+use crate::quantity::Time;7 10-/// Parameter value and whether it was used in the command line template8+/// Parameter value9 #[derive(Debug, Default, Clone, Serialize, PartialEq)]12-#[serde(transparent)]10 pub struct Parameter {11 pub value: String,15- #[serde(skip)]16- pub is_unused: bool,12 }13 14 /// Meta data and performance metrics for a single benchmark20-#[derive(Debug, Default, Clone, PartialEq)]15+#[derive(Debug, Default, Clone, Serialize, PartialEq)]16 pub struct BenchmarkResult {22- /// The full command line of the program that is being benchmarked17+ /// The command line being benchmarked, after parameter substitution.18+ /// For example, `sleep {duration}` with `duration=1` becomes `sleep 1`,19+ /// regardless of any custom name.20 pub command: String,21 25- /// The full command line, including parameters not used in the command template.26- pub command_with_unused_parameters: String,22+ /// The custom name after parameter substitution, if it differs from `command`.23+ /// For example, `--command-name="wait {duration}s"` with `duration=1`24+ /// produces `Some("wait 1s")`. Without a custom name, or when the expanded25+ /// name equals `command`, this is `None`.26+ #[serde(skip_serializing_if = "Option::is_none")]27+ pub name: Option<String>,28 28- /// Performance measurements and exit statuses for each run29+ /// The custom name (or `command`), followed by parameters not used in the30+ /// command template, in command-line order. For example, `sleep {duration}`31+ /// with `duration=1`, `branch=main`, and the custom name `wait {duration}s`32+ /// produces `wait 1s (branch = main)`. Without the custom name, this is33+ /// `sleep 1 (branch = main)`. Used in summaries and table exports.34+ #[serde(skip_serializing)]35+ pub display_name: String,36+37+ /// Performance metric measurements and exit codes for each run38+ #[serde(flatten)]39 pub measurements: Measurements,40 41 /// Parameter values for this benchmark42+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]43 pub parameters: BTreeMap<String, Parameter>,44 }45 46 impl BenchmarkResult {47+ pub fn get_name(&self) -> &str {48+ self.name.as_deref().unwrap_or(&self.command)49+ }50+51 /// The average wall clock time52 pub fn mean_wall_clock_time(&self) -> Time {53 self.measurements.time_wall_clock_mean()54 }55 }41-42-// Preserve the existing export format while storing typed measurements internally.43-impl Serialize for BenchmarkResult {44- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>45- where46- S: Serializer,47- {48- let mut state = serializer.serialize_struct(49- "BenchmarkResult",50- if self.parameters.is_empty() { 11 } else { 12 },51- )?;52- state.serialize_field("command", &self.command)?;53- state.serialize_field("mean", &self.mean_wall_clock_time().get::<second>())?;54- state.serialize_field(55- "stddev",56- &self.measurements.stddev().map(|time| time.get::<second>()),57- )?;58- state.serialize_field("median", &self.measurements.median().get::<second>())?;59- state.serialize_field("user", &self.measurements.time_user_mean().get::<second>())?;60- state.serialize_field(61- "system",62- &self.measurements.time_system_mean().get::<second>(),63- )?;64- state.serialize_field("min", &self.measurements.min().get::<second>())?;65- state.serialize_field("max", &self.measurements.max().get::<second>())?;66- state.serialize_field(67- "times",68- &self69- .measurements70- .wall_clock_times()71- .map(|time| time.get::<second>())72- .collect::<Vec<_>>(),73- )?;74- state.serialize_field(75- "memory_usage_byte",76- &self77- .measurements78- .measurements79- .iter()80- .map(|measurement| measurement.peak_memory_usage.get::<byte>() as u64)81- .collect::<Vec<_>>(),82- )?;83- state.serialize_field(84- "exit_codes",85- &self86- .measurements87- .measurements88- .iter()89- .map(|measurement| extract_exit_code(measurement.exit_status))90- .collect::<Vec<_>>(),91- )?;92- if !self.parameters.is_empty() {93- state.serialize_field("parameters", &self.parameters)?;94- }95- state.end()96- }97-}modified:src/benchmark/executor.rs+31 added-21 removed
1 #[cfg(windows)]2 use std::os::windows::process::CommandExt;3 use std::process::ExitStatus;4 5+use crate::benchmark::measurement::Measurement;6+use crate::benchmark::measurement::Measurements;7 use crate::command::Command;8 use crate::options::{9 CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,10 };1 unmodified line12 use crate::quantity::{second, Information, Time, Zero};13 use crate::timer::execute_and_measure;14 use crate::util::randomized_environment_offset;15 14-use super::measurement::{Measurement, Measurements};15-16 use anyhow::{bail, Context, Result};17 18 #[derive(Clone, Copy)]19 pub enum BenchmarkIteration {55 unmodified lines75 if let Some(value) = iteration.to_env_var_value() {76 command.env("HYPERFINE_ITERATION", value);77 }78 79- let result = execute_and_measure(command)79+ let measurement = execute_and_measure(command)80 .with_context(|| format!("Failed to run command '{command_name}'"))?;81 82- if !result.exit_status.success() {82+ if !measurement.exit_status.success() {83 use crate::util::exit_code::extract_exit_code;84 85 let should_fail = match command_failure_action {86 CmdFailureAction::RaiseError => true,87 CmdFailureAction::IgnoreAllFailures => false,88 CmdFailureAction::IgnoreSpecificFailures(ref codes) => {89 // Only fail if the exit code is not in the list of codes to ignore90- if let Some(exit_code) = extract_exit_code(result.exit_status) {90+ if let Some(exit_code) = extract_exit_code(measurement.exit_status) {91 !codes.contains(&exit_code)92 } else {93 // If we can't extract an exit code, treat it as a failure94 true11 unmodified lines106 };107 bail!(108 "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \109 Alternatively, use the '--show-output' option to debug what went wrong.",110- cause=result.exit_status.code().map_or(110+ cause=measurement.exit_status.code().map_or(111 "The process has been terminated by a signal".into(),112 |c| format!("Command terminated with non-zero exit code {c}")113 114 ),115 );116 }117 }118 119- Ok(result)119+ Ok(measurement)120 }121 122 pub struct RawExecutor<'a> {123 options: &'a Options,67 unmodified lines191 } else {192 command_builder.arg(command.get_command_line());193 }194 195- let mut result = run_command_and_measure_common(195+ let mut measurement = run_command_and_measure_common(196 command_builder,197 iteration,198 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),199 &self.options.command_input_policy,1 unmodified line201 &command.get_command_line(),202 )?;203 204 // Subtract shell spawning time205- if let Some(spawning_time) = self.shell_spawning_time {206- result.time_wall_clock =207- (result.time_wall_clock - spawning_time.time_wall_clock).max(Time::zero());208- result.time_user = (result.time_user - spawning_time.time_user).max(Time::zero());209- result.time_system = (result.time_system - spawning_time.time_system).max(Time::zero());205+ fn ensure_non_negative(time: Time) -> Time {206+ if time < Time::zero() {207+ Time::zero()208+ } else {209+ time210+ }211 }212 212- Ok(result)213+ if let Some(ref spawning_time) = self.shell_spawning_time {214+ measurement.time_wall_clock =215+ ensure_non_negative(measurement.time_wall_clock - spawning_time.time_wall_clock);216+ measurement.time_user =217+ ensure_non_negative(measurement.time_user - spawning_time.time_user);218+ measurement.time_system =219+ ensure_non_negative(measurement.time_system - spawning_time.time_system);220+ }221+222+ Ok(measurement)223 }224 225 /// Measure the average shell spawning time226 fn calibrate(&mut self) -> Result<()> {11 unmodified lines238 let mut measurements = Measurements::default();239 240 for _ in 0..COUNT {241 // Just run the shell without any command232- let res = self.run_command_and_measure(242+ let measurement = self.run_command_and_measure(243 &Command::new(None, ""),244 BenchmarkIteration::NonBenchmarkRun,245 None,246 &CommandOutputPolicy::Null,247 );248 239- match res {249+ match measurement {250 Err(_) => {251 let shell_cmd = if cfg!(windows) {252 format!("{} /C \"\"", self.shell)253 } else {4 unmodified lines258 "Could not measure shell execution time. Make sure you can run '{}'.",259 shell_cmd260 );261 }252- Ok(r) => {253- measurements.push(r);262+ Ok(result) => {263+ measurements.push(result);264 }265 }266 267 if let Some(bar) = progress_bar.as_ref() {8 unmodified lines276 self.shell_spawning_time = Some(Measurement {277 time_wall_clock: measurements.time_wall_clock_mean(),278 time_user: measurements.time_user_mean(),279 time_system: measurements.time_system_mean(),270- peak_memory_usage: measurements.peak_memory_usage_mean(),280+ memory_peak_resident: None,281 exit_status: ExitStatus::default(),282 });283 284 Ok(())285 }286 287 fn time_overhead(&self) -> Time {278- self.shell_spawning_time.unwrap().time_wall_clock288+ self.shell_spawning_time.as_ref().unwrap().time_wall_clock289 }290 }291 292 #[derive(Clone)]41 unmodified lines334 Ok(Measurement {335 time_wall_clock: Self::extract_time(command.get_command_line()),336 time_user: Time::zero(),337 time_system: Time::zero(),328- peak_memory_usage: Information::zero(),338+ memory_peak_resident: Some(Information::zero()),339 exit_status,340 })341 }342 19 unmodified linesmodified:src/benchmark/measurement.rs+49 added-20 removed
1 use std::process::ExitStatus;2 3+use serde::Serialize;4+5 use crate::quantity::statistics::{max, mean, median, min, modified_zscores, standard_deviation};4-use crate::quantity::{Information, Time};6+use crate::quantity::{serialize_information, serialize_time, Information, Time};7+use crate::util::exit_code::extract_exit_code;8 6-/// Performance measurements and exit status from running a single command7-#[derive(Debug, Default, Copy, Clone, PartialEq)]9+fn serialize_exit_status<S>(exit_status: &ExitStatus, serializer: S) -> Result<S::Ok, S::Error>10+where11+ S: serde::Serializer,12+{13+ match extract_exit_code(*exit_status) {14+ Some(code) => serializer.serialize_i32(code),15+ None => serializer.serialize_unit(),16+ }17+}18+19+fn serialize_optional_information<S>(20+ value: &Option<Information>,21+ serializer: S,22+) -> Result<S::Ok, S::Error>23+where24+ S: serde::Serializer,25+{26+ match value {27+ Some(value) => serialize_information(value, serializer),28+ None => serializer.serialize_none(),29+ }30+}31+32+/// Performance metric measurements and exit code for a single run33+#[derive(Debug, Clone, Default, Serialize, PartialEq)]34 pub struct Measurement {9- /// Wall clock time35+ /// Elapsed wall clock time (real time)36+ #[serde(serialize_with = "serialize_time")]37 pub time_wall_clock: Time,38 39 /// Time spent in user mode40+ #[serde(serialize_with = "serialize_time")]41 pub time_user: Time,42 43 /// Time spent in kernel mode44+ #[serde(serialize_with = "serialize_time")]45 pub time_system: Time,46 18- /// Maximum amount of memory used19- pub peak_memory_usage: Information,47+ /// Peak resident set size, if available on this platform48+ #[serde(49+ skip_serializing_if = "Option::is_none",50+ serialize_with = "serialize_optional_information"51+ )]52+ pub memory_peak_resident: Option<Information>,53 21- /// The exit status of the process54+ // The exit status of the process55+ #[serde(rename = "exit_code", serialize_with = "serialize_exit_status")]56 pub exit_status: ExitStatus,57 }58 25-/// Performance measurements and exit statuses for all runs of a command.26-#[derive(Debug, Default, Clone, PartialEq)]59+#[derive(Debug, Default, Clone, Serialize, PartialEq)]60 pub struct Measurements {61 pub measurements: Vec<Measurement>,62 }63 17 unmodified lines81 pub fn wall_clock_times(&self) -> impl Iterator<Item = Time> + '_ {82 self.measurements.iter().map(|m| m.time_wall_clock)83 }84 52- /// The average wall clock time.85+ /// The average wall clock time86 pub fn time_wall_clock_mean(&self) -> Time {87 mean(self.wall_clock_times())88 }89 7 unmodified lines97 Some(standard_deviation(times))98 }99 }100 68- /// The median wall clock time.101+ /// The median wall clock time102 pub fn median(&self) -> Time {103 median(self.wall_clock_times())104 }105 73- /// The minimum wall clock time.106+ /// The minimum wall clock time107 pub fn min(&self) -> Time {108 min(self.wall_clock_times())109 }110 78- /// The maximum wall clock time.111+ /// The maximum wall clock time112 pub fn max(&self) -> Time {113 max(self.wall_clock_times())114 }115 83- /// Compute modified Z-scores for the wall clock times.116+ /// Compute modified Z-scores for the wall clock times117 pub fn modified_zscores(&self) -> Vec<f64> {118 modified_zscores(&self.wall_clock_times().collect::<Vec<_>>())119 }120 88- /// The average user time.121+ /// The average user time122 pub fn time_user_mean(&self) -> Time {123 mean(self.measurements.iter().map(|m| m.time_user))124 }125 93- /// The average system time.126+ /// The average system time127 pub fn time_system_mean(&self) -> Time {128 mean(self.measurements.iter().map(|m| m.time_system))129 }97-98- pub fn peak_memory_usage_mean(&self) -> Information {99- mean(self.measurements.iter().map(|m| m.peak_memory_usage))100- }130 }modified:src/benchmark/mod.rs+34 added-36 removed
6 unmodified lines7 use std::cmp;8 use std::io::{self, Write};9 use std::time::Instant;10 11+use crate::benchmark::benchmark_result::Parameter;12 use crate::benchmark::executor::BenchmarkIteration;13+use crate::benchmark::measurement::{Measurement, Measurements};14 use crate::command::Command;15 use crate::options::{16 CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,17 };3 unmodified lines21 finish_initial_measurement, get_progress_bar, start_initial_measurement,22 };23 use crate::output::warnings::{OutlierWarningOptions, Warnings};24 use crate::parameter::ParameterNameAndValue;23-use crate::quantity::{const_time_from_seconds, ratio, FormatQuantity, Time, Zero};24-use benchmark_result::{BenchmarkResult, Parameter};25-use measurement::{Measurement, Measurements};25+use crate::quantity::{self, const_time_from_seconds, FormatQuantity, Time, Zero};26+use benchmark_result::BenchmarkResult;27 28 use anyhow::{anyhow, Result};29 use colored::*;30 31 use self::executor::Executor;32 33 /// Threshold for warning about fast execution time33-pub const MIN_EXECUTION_TIME: Time = const_time_from_seconds(5e-3);34+pub const MIN_EXECUTION_TIME: Time = const_time_from_seconds(0.005);35 36 pub struct Benchmark<'a> {37 number: usize,38 command: &'a Command<'a>,229 unmodified lines268 // Initial timing run269 if let Some(bar) = progress_bar.as_ref() {270 start_initial_measurement(bar, Instant::now());271 }271- let res = self.executor.run_command_and_measure(272+ let measurement = self.executor.run_command_and_measure(273 self.command,274 benchmark_iteration,275 None,276 output_policy,277 )?;277- let success = res.exit_status.success();278+ let success = measurement.exit_status.success();279 280 if let Some(bar) = progress_bar.as_ref() {281 let time_unit = self282 .options283 .time_unit283- .unwrap_or(res.time_wall_clock.suitable_unit());284- let estimate = res.time_wall_clock.format(time_unit);284+ .unwrap_or(measurement.time_wall_clock.suitable_unit());285+ let estimate = measurement.time_wall_clock.format(time_unit);286 finish_initial_measurement(287 bar,288 format!("Current estimate: {}", estimate.to_string().green()),289 );5 unmodified lines295 });296 297 // Determine number of benchmark runs298 let runs_in_min_time = (self.options.min_benchmarking_time298- / (res.time_wall_clock299+ / (measurement.time_wall_clock300 + self.executor.time_overhead()301 + preparation_overhead302 + conclusion_overhead))302- .get::<ratio>() as u64;303+ .get::<quantity::ratio>() as u64;304 305 let count = {306 let min = cmp::max(runs_in_min_time, self.options.run_bounds.min);307 7 unmodified lines315 316 let count_remaining = count - 1;317 318 // Save the first result318- measurements.push(res);319+ measurements.push(measurement);320 321 all_succeeded = all_succeeded && success;322 323 // Re-configure the progress bar21 unmodified lines345 }346 347 run_preparation_command(benchmark_iteration)?;348 348- let res = self.executor.run_command_and_measure(349+ let measurement = self.executor.run_command_and_measure(350 self.command,351 benchmark_iteration,352 None,353 output_policy,354 )?;354- let success = res.exit_status.success();355+ let success = measurement.exit_status.success();356+ measurements.push(measurement);357 356- measurements.push(res);357-358 all_succeeded = all_succeeded && success;359 360 if let Some(bar) = progress_bar.as_ref() {361 bar.inc(1)5 unmodified lines367 if let Some(bar) = progress_bar.as_ref() {368 bar.finish_and_clear()369 }370 371- // Compute statistical quantities372- let t_num = measurements.len();373- let t_mean = measurements.time_wall_clock_mean();374- let t_stddev = measurements.stddev();375- let t_min = measurements.min();376- let t_max = measurements.max();377-378- let user_mean = measurements.time_user_mean();379- let system_mean = measurements.time_system_mean();380-371 // Formatting and console output382- let time_unit = self.options.time_unit.unwrap_or(t_mean.suitable_unit());383- let mean_str = t_mean.format(time_unit);384- let min_str = t_min.format(time_unit);385- let max_str = t_max.format(time_unit);386- let num_str = format!("{t_num} runs");372+ let t_wall_clock_mean = measurements.time_wall_clock_mean();373+ let time_unit = self374+ .options375+ .time_unit376+ .unwrap_or(t_wall_clock_mean.suitable_unit());377+ let mean_str = t_wall_clock_mean.format(time_unit);378+ let min_str = measurements.min().format(time_unit);379+ let max_str = measurements.max().format(time_unit);380+ let num_str = format!("{num_runs} runs", num_runs = measurements.len());381 388- let user_str = user_mean.format(time_unit);389- let system_str = system_mean.format(time_unit);382+ let user_str = measurements.time_user_mean().format(time_unit);383+ let system_str = measurements.time_system_mean().format(time_unit);384 385 if self.options.output_style != OutputStyleOption::Disabled {386 let mut stdout = io::stdout().lock();387 if measurements.len() == 1 {6 unmodified lines394 user_str.blue(),395 system_str.blue()396 )?;397 } else {404- let stddev_str = t_stddev.unwrap().format(time_unit);398+ let stddev_str = measurements.stddev().unwrap().format(time_unit);399 400 console_writeln!(401 stdout,402 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",71 unmodified lines474 }475 476 self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;477 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 {485- command: self.command.get_name(),486- command_with_unused_parameters: self.command.get_name_with_unused_parameters(),483+ command,484+ name,485+ display_name: self.command.get_name_with_unused_parameters(),486 measurements,487 parameters: self488 .command489 .get_parameters()2 unmodified lines492 (493 name.to_string(),494 Parameter {495 value: value.to_string(),497- is_unused: self.command.is_parameter_unused(name),496 },497 )498 })499 .collect(),3 unmodified linesmodified:src/benchmark/relative_speed.rs+4 added-3 removed
152 unmodified lines153 fn create_result(name: &str, mean: f64) -> BenchmarkResult {154 use std::collections::BTreeMap;155 156 use crate::benchmark::measurement::{Measurement, Measurements};157- use crate::quantity::{second, Time};157+ use crate::quantity::second;158 159 BenchmarkResult {160 command: name.into(),161- command_with_unused_parameters: name.into(),161+ display_name: name.into(),162+ name: None,163 measurements: Measurements {164 measurements: vec![Measurement {165 time_wall_clock: Time::new::<second>(mean),166 time_user: Time::new::<second>(mean),56 unmodified lines223 #[test]224 fn reference_ratios_handle_zero_times() {225 let mut results = vec![create_result("reference", 2.0), create_result("zero", 0.0)];226 for result in &mut results {226- let measurement = result.measurements.measurements[0];227+ let measurement = result.measurements.measurements[0].clone();228 result.measurements.measurements.push(measurement);229 }230 let entries = compute_relative_speeds(&results, &results[0], SortOrder::Command);231 assert_eq!(entries[1].relative_speed, f64::INFINITY);6 unmodified linesmodified:src/benchmark/scheduler.rs+57 added-39 removed
87 unmodified lines88 89 let reference = annotated_results.iter().find(|r| r.is_reference).unwrap();90 let others = annotated_results.iter().filter(|r| !r.is_reference);91 92- console_writeln!(93- stdout,94- " {} ran",95- reference.result.command_with_unused_parameters.cyan()96- )?;92+ console_writeln!(stdout, " {} ran", reference.result.display_name.cyan())?;93 94 for item in others {95 let stddev = if let Some(stddev) = item.relative_speed_stddev {96 format!(" ± {}", format!("{:.2}", stddev).green())20 unmodified lines117 console_writeln!(118 stdout,119 "{} {}",120 comparator,125- item.result.command_with_unused_parameters.magenta()121+ &item.result.display_name.magenta()122 )?;123 }124 }125 SortOrder::Command => {15 unmodified lines141 format!(" ± {}", format!("{stddev:5.2}").green())142 } else {143 " ".into()144 },149- item.result.command_with_unused_parameters,145+ item.result.display_name,146 relationship,147 )?;148 }149 }50 unmodified lines200 #[test]201 fn scheduler_basic() -> Result<()> {202 insta::assert_yaml_snapshot!(generate_results(&["--runs=2", "sleep 0.123", "sleep 0.456"])?, @r#"203 - command: sleep 0.123208- mean: 0.123209- stddev: 0210- median: 0.123211- user: 0212- system: 0213- min: 0.123214- max: 0.123215- times:216- - 0.123217- - 0.123218- memory_usage_byte:219- - 0220- - 0221- exit_codes:222- - 0223- - 0204+ measurements:205+ - time_wall_clock:206+ value: 0.123207+ unit: second208+ time_user:209+ value: 0210+ unit: second211+ time_system:212+ value: 0213+ unit: second214+ memory_peak_resident:215+ value: 0216+ unit: byte217+ exit_code: 0218+ - time_wall_clock:219+ value: 0.123220+ unit: second221+ time_user:222+ value: 0223+ unit: second224+ time_system:225+ value: 0226+ unit: second227+ memory_peak_resident:228+ value: 0229+ unit: byte230+ exit_code: 0231 - command: sleep 0.456225- mean: 0.456226- stddev: 0227- median: 0.456228- user: 0229- system: 0230- min: 0.456231- max: 0.456232- times:233- - 0.456234- - 0.456235- memory_usage_byte:236- - 0237- - 0238- exit_codes:239- - 0240- - 0232+ measurements:233+ - time_wall_clock:234+ value: 0.456235+ unit: second236+ time_user:237+ value: 0238+ unit: second239+ time_system:240+ value: 0241+ unit: second242+ memory_peak_resident:243+ value: 0244+ unit: byte245+ exit_code: 0246+ - time_wall_clock:247+ value: 0.456248+ unit: second249+ time_user:250+ value: 0251+ unit: second252+ time_system:253+ value: 0254+ unit: second255+ memory_peak_resident:256+ value: 0257+ unit: byte258+ exit_code: 0259 "#);260 261 Ok(())262 }added:src/export/json/metadata.rs+51 added
1+use serde::Serialize;2+3+#[derive(Debug, Serialize)]4+pub(super) struct Metadata {5+ hyperfine_version: &'static str,6+ #[serde(skip_serializing_if = "Option::is_none")]7+ pub start_time: Option<String>,8+ pub platform: Platform,9+}10+11+impl Default for Metadata {12+ fn default() -> Self {13+ Self {14+ hyperfine_version: env!("CARGO_PKG_VERSION"),15+ start_time: utc_now(),16+ platform: Platform::detect(),17+ }18+ }19+}20+21+fn utc_now() -> Option<String> {22+ use std::{fmt::Write, time::SystemTime};23+24+ let now = SystemTime::now();25+ now.duration_since(SystemTime::UNIX_EPOCH).ok()?;26+ let mut timestamp = String::new();27+ write!(&mut timestamp, "{}", humantime::format_rfc3339_seconds(now)).ok()?;28+ Some(timestamp)29+}30+31+#[derive(Debug, Default, Serialize)]32+pub(super) struct Platform {33+ #[serde(skip_serializing_if = "Option::is_none")]34+ os: Option<String>,35+ #[serde(skip_serializing_if = "Option::is_none")]36+ architecture: Option<String>,37+}38+39+impl Platform {40+ fn detect() -> Self {41+ use platform_info::{PlatformInfo, PlatformInfoAPI, UNameAPI};42+43+ let Ok(info) = PlatformInfo::new() else {44+ return Self::default();45+ };46+ Self {47+ os: Some(info.sysname().to_string_lossy().into_owned()),48+ architecture: Some(info.machine().to_string_lossy().into_owned()),49+ }50+ }51+}modified:src/export/csv.rs+13 added-15 removed
14 unmodified lines15 impl Exporter for CsvExporter {16 fn serialize(17 &self,18 results: &[BenchmarkResult],19- _unit: Option<TimeUnit>,19+ _time_unit: Option<TimeUnit>,20 _sort_order: SortOrder,21 _reference_index: Option<usize>,22 ) -> Result<Vec<u8>> {23 const CSV_UNIT: TimeUnit = TimeUnit::Second;17 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_with_unused_parameters: String::from("command_a"),83+ command: String::from("echo command_a"),84+ name: Some(String::from("command_a")),85+ display_name: String::from("command_a"),86 measurements: Measurements::new(vec![87 Measurement {88 time_wall_clock: Time::new::<second>(7.0),89 time_user: Time::new::<second>(7.0),90 time_system: Time::zero(),90- peak_memory_usage: Information::new::<byte>(1024.),91+ memory_peak_resident: Some(Information::new::<byte>(1024.)),92 exit_status: ExitStatus::default(),93 },94 Measurement {95 time_wall_clock: Time::new::<second>(8.0),96 time_user: Time::new::<second>(8.0),97 time_system: Time::zero(),97- peak_memory_usage: Information::new::<byte>(1024.),98+ memory_peak_resident: Some(Information::new::<byte>(1024.)),99 exit_status: ExitStatus::default(),100 },101 Measurement {102 time_wall_clock: Time::new::<second>(12.0),103 time_user: Time::new::<second>(12.0),104 time_system: Time::zero(),104- peak_memory_usage: Information::new::<byte>(1024.),105+ memory_peak_resident: Some(Information::new::<byte>(1024.)),106 exit_status: ExitStatus::default(),107 },108 ]),109 parameters: {1 unmodified line111 params.insert(112 "foo".into(),113 Parameter {114 value: "one".into(),114- is_unused: false,115 },116 );117 params.insert(118 "bar".into(),119 Parameter {120 value: "two".into(),121- is_unused: false,121 },122 );123 params124 },125 },126 BenchmarkResult {127 command: String::from("command_b"),129- command_with_unused_parameters: String::from("command_b"),128+ name: None,129+ display_name: String::from("command_b"),130 measurements: Measurements::new(vec![131 Measurement {132 time_wall_clock: Time::new::<second>(17.0),133 time_user: Time::new::<second>(17.0),134 time_system: Time::zero(),135- peak_memory_usage: Information::new::<byte>(1024.),135+ memory_peak_resident: Some(Information::new::<byte>(1024.)),136 exit_status: ExitStatus::default(),137 },138 Measurement {139 time_wall_clock: Time::new::<second>(18.0),140 time_user: Time::new::<second>(18.0),141 time_system: Time::zero(),142- peak_memory_usage: Information::new::<byte>(1024.),142+ memory_peak_resident: Some(Information::new::<byte>(1024.)),143 exit_status: ExitStatus::default(),144 },145 Measurement {146 time_wall_clock: Time::new::<second>(19.0),147 time_user: Time::new::<second>(19.0),148 time_system: Time::zero(),149- peak_memory_usage: Information::new::<byte>(1024.),149+ memory_peak_resident: Some(Information::new::<byte>(1024.)),150 exit_status: ExitStatus::default(),151 },152 ]),153 parameters: {1 unmodified line155 params.insert(156 "foo".into(),157 Parameter {158 value: "one".into(),159- is_unused: false,159 },160 );161 params.insert(162 "bar".into(),163 Parameter {164 value: "seven".into(),166- is_unused: false,165 },166 );167 params168 },16 unmodified linesmodified:src/export/json.rs+148 added-7 removed
1+use std::ops::{Add, AddAssign, Div};2+3 use serde::*;4 use serde_json::to_vec_pretty;5 6 use super::Exporter;7 use crate::benchmark::benchmark_result::BenchmarkResult;8+use crate::benchmark::measurement::Measurements;9 use crate::options::SortOrder;7-use crate::quantity::TimeUnit;10+use crate::quantity::statistics::{max, mean, median, min, standard_deviation, UnsafeRawValue};11+use crate::quantity::{byte, second, QuantityInUnit, Ratio, TimeUnit, Zero};12 13 use anyhow::Result;14 15+mod metadata;16+use metadata::Metadata;17+18+const JSON_SCHEMA_VERSION: u32 = 2;19+11-#[derive(Serialize, Debug)]20+#[derive(Serialize)]21 struct HyperfineSummary<'a> {13- results: &'a [BenchmarkResult],22+ schema_version: u32,23+ metadata: &'a Metadata,24+ results: Vec<JsonBenchmarkResult<'a>>,25 }26 27+#[derive(Serialize)]28+struct JsonBenchmarkResult<'a> {29+ #[serde(flatten)]30+ result: &'a BenchmarkResult,31+ #[serde(skip_serializing_if = "std::ops::Not::not")]32+ is_reference: bool,33+ summary: BenchmarkSummary,34+}35+36+#[derive(Serialize)]37+struct BenchmarkSummary {38+ time_wall_clock: StatisticalSummary,39+ time_user: StatisticalSummary,40+ time_system: StatisticalSummary,41+ #[serde(skip_serializing_if = "Option::is_none")]42+ memory_peak_resident: Option<StatisticalSummary>,43+}44+45+impl BenchmarkSummary {46+ fn from_measurements(measurements: &Measurements) -> Self {47+ let values = &measurements.measurements;48+ let mut memory_values = values49+ .iter()50+ .filter_map(|m| m.memory_peak_resident)51+ .peekable();52+ Self {53+ time_wall_clock: StatisticalSummary::from_values(54+ values.iter().map(|m| m.time_wall_clock),55+ second,56+ ),57+ time_user: StatisticalSummary::from_values(values.iter().map(|m| m.time_user), second),58+ time_system: StatisticalSummary::from_values(59+ values.iter().map(|m| m.time_system),60+ second,61+ ),62+ memory_peak_resident: memory_values63+ .peek()64+ .is_some()65+ .then(|| StatisticalSummary::from_values(memory_values, byte)),66+ }67+ }68+}69+70+#[derive(Serialize)]71+struct StatisticalSummary {72+ unit: &'static str,73+ count: usize,74+ mean: f64,75+ stddev: Option<f64>,76+ median: f64,77+ min: f64,78+ max: f64,79+}80+81+impl StatisticalSummary {82+ fn from_values<Q, P, U>(values: impl IntoIterator<Item = Q>, _unit: U) -> Self83+ where84+ Q: Copy85+ + PartialOrd86+ + Add<Output = Q>87+ + AddAssign88+ + Zero89+ + Div<Ratio, Output = P>90+ + UnsafeRawValue91+ + QuantityInUnit<U>,92+ P: Into<Q>,93+ U: uom::si::Unit,94+ {95+ let values: Vec<_> = values.into_iter().collect();96+ assert!(97+ !values.is_empty(),98+ "Statistical summaries require at least one measurement"99+ );100+ Self {101+ unit: U::singular(),102+ count: values.len(),103+ mean: mean(values.iter().copied()).value_in_unit(),104+ stddev: (values.len() > 1)105+ .then(|| standard_deviation(values.iter().copied()).value_in_unit()),106+ median: median(values.iter().copied()).value_in_unit(),107+ min: min(values.iter().copied()).value_in_unit(),108+ max: max(values.iter().copied()).value_in_unit(),109+ }110+ }111+}112+113 #[derive(Default)]17-pub struct JsonExporter {}114+pub struct JsonExporter {115+ metadata: Metadata,116+}117 118 impl Exporter for JsonExporter {119 fn serialize(120 &self,121 results: &[BenchmarkResult],23- _unit: Option<TimeUnit>,122+ _time_unit: Option<TimeUnit>,123 _sort_order: SortOrder,25- _reference_index: Option<usize>,124+ reference_index: Option<usize>,125 ) -> Result<Vec<u8>> {27- let mut output = to_vec_pretty(&HyperfineSummary { results });126+ let mut output = to_vec_pretty(&HyperfineSummary {127+ schema_version: JSON_SCHEMA_VERSION,128+ metadata: &self.metadata,129+ results: results130+ .iter()131+ .enumerate()132+ .map(|(index, result)| JsonBenchmarkResult {133+ result,134+ is_reference: reference_index == Some(index),135+ summary: BenchmarkSummary::from_measurements(&result.measurements),136+ })137+ .collect(),138+ });139 if let Ok(ref mut content) = output {140 content.push(b'\n');141 }142 143 Ok(output?)144 }145 }146+147+#[test]148+fn test_statistical_summary_unit_conversion() {149+ use crate::quantity::{kibibyte, millisecond, Information, Time};150+151+ let time = StatisticalSummary::from_values(152+ [Time::new::<second>(1.0), Time::new::<second>(3.0)],153+ millisecond,154+ );155+ let information = StatisticalSummary::from_values(156+ [157+ Information::new::<byte>(1024.0),158+ Information::new::<byte>(3072.0),159+ ],160+ kibibyte,161+ );162+163+ for (summary, unit, scale) in [164+ (time, "millisecond", 1000.0),165+ (information, "kibibyte", 1.0),166+ ] {167+ assert_eq!(summary.unit, unit);168+ assert_eq!(summary.count, 2);169+ approx::assert_relative_eq!(summary.mean, 2.0 * scale);170+ approx::assert_relative_eq!(summary.median, 2.0 * scale);171+ approx::assert_relative_eq!(summary.min, scale);172+ approx::assert_relative_eq!(summary.max, 3.0 * scale);173+ approx::assert_relative_eq!(summary.stddev.unwrap(), 2.0_f64.sqrt() * scale);174+ }175+}modified:src/export/markup.rs+12 added-14 removed
14 unmodified lines15 pub trait MarkupExporter {16 fn table_results(17 &self,18 entries: &[BenchmarkResultWithRelativeSpeed],19- unit: TimeUnit,19+ time_unit: TimeUnit,20 reference_pending: bool,21 explicit_reference: bool,22 ) -> String {23 // prepare table header strings24- let notation = format!("[{}]", unit.short_name());24+ let notation = format!("[{}]", time_unit.short_name());25 26 // prepare table cells alignment27 let cells_alignment = [28 Alignment::Left,18 unmodified lines47 // emit horizontal line48 table.push_str(&self.table_divider(&cells_alignment));49 50 for entry in entries {51- let measurement = &entry.result;51+ let result = &entry.result;52 // prepare data row strings53- let cmd_str = measurement54- .command_with_unused_parameters55- .replace('|', "\\|");56- let mean_str = measurement.mean_wall_clock_time().format_value(unit);57- let stddev_str = if let Some(stddev) = measurement.measurements.stddev() {58- format!(" ± {}", stddev.format_value(unit))53+ let cmd_str = result.display_name.replace('|', "\\|");54+ let mean_str = result.mean_wall_clock_time().format_value(time_unit);55+ let stddev_str = if let Some(stddev) = result.measurements.stddev() {56+ format!(" ± {}", stddev.format_value(time_unit))57 } else {58 "".into()59 };62- let min_str = measurement.measurements.min().format_value(unit);63- let max_str = measurement.measurements.max().format_value(unit);60+ let min_str = result.measurements.min().format_value(time_unit);61+ let max_str = result.measurements.max().format_value(time_unit);62 // The ratio of two zero times is undefined, even if they compare equal.63 let relative_unavailable = reference_pending64 || (explicit_reference65 && !entry.is_reference66 && entry.relative_ordering == Ordering::Equal69- && measurement.mean_wall_clock_time() == Time::zero());67+ && result.mean_wall_clock_time() == Time::zero());68 let relative = if relative_unavailable {69 "N/A".to_string()70 } else {71 let stddev = match (entry.is_reference, entry.relative_speed_stddev) {52 unmodified lines124 impl<T: MarkupExporter> Exporter for T {125 fn serialize(126 &self,127 results: &[BenchmarkResult],130- unit: Option<TimeUnit>,128+ time_unit: Option<TimeUnit>,129 sort_order: SortOrder,130 reference_index: Option<usize>,131 ) -> Result<Vec<u8>> {134- let unit = unit.unwrap_or_else(|| determine_unit_from_results(results));132+ let unit = time_unit.unwrap_or_else(|| determine_unit_from_results(results));133 // Do not report ratios against another benchmark while the selected134 // reference is still pending in an intermediate export.135 let reference_pending = reference_index.is_some_and(|i| i >= results.len());136 let entries = relative_speed::compute(10 unmodified linesmodified:src/export/mod.rs+1 added-1 removed
47 unmodified lines48 /// Export the given entries in the serialized form.49 fn serialize(50 &self,51 results: &[BenchmarkResult],52- unit: Option<TimeUnit>,52+ time_unit: Option<TimeUnit>,53 sort_order: SortOrder,54 reference_index: Option<usize>,55 ) -> Result<Vec<u8>>;56 }120 unmodified linesmodified:src/export/tests.rs+40 added-32 removed
26 unmodified lines27 fn test_markup_export_auto_ms() {28 let results = [29 BenchmarkResult {30 command: String::from("sleep 0.1"),31- command_with_unused_parameters: String::from("sleep 0.1"),31+ name: None,32+ display_name: String::from("sleep 0.1"),33 measurements: Measurements::new(vec![34 Measurement {35 time_wall_clock: Time::new::<second>(0.09),36 time_user: Time::new::<second>(0.09),37 time_system: Time::zero(),37- peak_memory_usage: Information::new::<byte>(1024.),38+ memory_peak_resident: Some(Information::new::<byte>(1024.)),39 exit_status: ExitStatus::default(),40 },41 Measurement {42 time_wall_clock: Time::new::<second>(0.10),43 time_user: Time::new::<second>(0.10),44 time_system: Time::zero(),44- peak_memory_usage: Information::new::<byte>(1024.),45+ memory_peak_resident: Some(Information::new::<byte>(1024.)),46 exit_status: ExitStatus::default(),47 },48 Measurement {49 time_wall_clock: Time::new::<second>(0.14),50 time_user: Time::new::<second>(0.14),51 time_system: Time::zero(),51- peak_memory_usage: Information::new::<byte>(1024.),52+ memory_peak_resident: Some(Information::new::<byte>(1024.)),53 exit_status: ExitStatus::default(),54 },55 ]),56 parameters: BTreeMap::new(),57 },58 BenchmarkResult {59 command: String::from("sleep 2"),59- command_with_unused_parameters: String::from("sleep 2"),60+ name: None,61+ display_name: String::from("sleep 2"),62 measurements: Measurements::new(vec![63 Measurement {64 time_wall_clock: Time::new::<second>(2.0),65 time_user: Time::new::<second>(2.0),66 time_system: Time::zero(),65- peak_memory_usage: Information::new::<byte>(1024.),67+ memory_peak_resident: Some(Information::new::<byte>(1024.)),68 exit_status: ExitStatus::default(),69 },70 Measurement {71 time_wall_clock: Time::new::<second>(3.0),72 time_user: Time::new::<second>(3.0),73 time_system: Time::zero(),72- peak_memory_usage: Information::new::<byte>(1024.),74+ memory_peak_resident: Some(Information::new::<byte>(1024.)),75 exit_status: ExitStatus::default(),76 },77 Measurement {78 time_wall_clock: Time::new::<second>(4.0),79 time_user: Time::new::<second>(4.0),80 time_system: Time::zero(),79- peak_memory_usage: Information::new::<byte>(1024.),81+ memory_peak_resident: Some(Information::new::<byte>(1024.)),82 exit_status: ExitStatus::default(),83 },84 ]),85 parameters: BTreeMap::new(),44 unmodified lines130 fn test_markup_export_auto_s() {131 let results = [132 BenchmarkResult {133 command: String::from("sleep 2"),132- command_with_unused_parameters: String::from("sleep 2"),134+ name: None,135+ display_name: String::from("sleep 2"),136 measurements: Measurements::new(vec![137 Measurement {138 time_wall_clock: Time::new::<second>(2.1),139 time_user: Time::new::<second>(2.1),140 time_system: Time::zero(),138- peak_memory_usage: Information::new::<byte>(1024.),141+ memory_peak_resident: Some(Information::new::<byte>(1024.)),142 exit_status: ExitStatus::default(),143 },144 Measurement {145 time_wall_clock: Time::new::<second>(2.2),146 time_user: Time::new::<second>(2.2),147 time_system: Time::zero(),145- peak_memory_usage: Information::new::<byte>(1024.),148+ memory_peak_resident: Some(Information::new::<byte>(1024.)),149 exit_status: ExitStatus::default(),150 },151 Measurement {152 time_wall_clock: Time::new::<second>(2.3),153 time_user: Time::new::<second>(2.3),154 time_system: Time::zero(),152- peak_memory_usage: Information::new::<byte>(1024.),155+ memory_peak_resident: Some(Information::new::<byte>(1024.)),156 exit_status: ExitStatus::default(),157 },158 ]),159 parameters: BTreeMap::new(),160 },161 BenchmarkResult {162 command: String::from("sleep 0.1"),160- command_with_unused_parameters: String::from("sleep 0.1"),163+ name: None,164+ display_name: String::from("sleep 0.1"),165 measurements: Measurements::new(vec![166 Measurement {167 time_wall_clock: Time::new::<second>(0.1),168 time_user: Time::new::<second>(0.1),169 time_system: Time::zero(),166- peak_memory_usage: Information::new::<byte>(1024.),170+ memory_peak_resident: Some(Information::new::<byte>(1024.)),171 exit_status: ExitStatus::default(),172 },173 Measurement {174 time_wall_clock: Time::new::<second>(0.2),175 time_user: Time::new::<second>(0.2),176 time_system: Time::zero(),173- peak_memory_usage: Information::new::<byte>(1024.),177+ memory_peak_resident: Some(Information::new::<byte>(1024.)),178 exit_status: ExitStatus::default(),179 },180 Measurement {181 time_wall_clock: Time::new::<second>(0.3),182 time_user: Time::new::<second>(0.3),183 time_system: Time::zero(),180- peak_memory_usage: Information::new::<byte>(1024.),184+ memory_peak_resident: Some(Information::new::<byte>(1024.)),185 exit_status: ExitStatus::default(),186 },187 ]),188 parameters: BTreeMap::new(),44 unmodified lines233 fn test_markup_export_manual_ms() {234 let timing_results = [235 BenchmarkResult {236 command: String::from("sleep 2"),233- command_with_unused_parameters: String::from("sleep 2"),237+ name: None,238+ display_name: String::from("sleep 2"),239 measurements: Measurements::new(vec![240 Measurement {241 time_wall_clock: Time::new::<second>(2.1),242 time_user: Time::new::<second>(2.1),243 time_system: Time::zero(),239- peak_memory_usage: Information::new::<byte>(1024.),244+ memory_peak_resident: Some(Information::new::<byte>(1024.)),245 exit_status: ExitStatus::default(),246 },247 Measurement {248 time_wall_clock: Time::new::<second>(2.2),249 time_user: Time::new::<second>(2.2),250 time_system: Time::zero(),246- peak_memory_usage: Information::new::<byte>(1024.),251+ memory_peak_resident: Some(Information::new::<byte>(1024.)),252 exit_status: ExitStatus::default(),253 },254 Measurement {255 time_wall_clock: Time::new::<second>(2.3),256 time_user: Time::new::<second>(2.3),257 time_system: Time::zero(),253- peak_memory_usage: Information::new::<byte>(1024.),258+ memory_peak_resident: Some(Information::new::<byte>(1024.)),259 exit_status: ExitStatus::default(),260 },261 ]),262 parameters: BTreeMap::new(),263 },264 BenchmarkResult {265 command: String::from("sleep 0.1"),261- command_with_unused_parameters: String::from("sleep 0.1"),266+ name: None,267+ display_name: String::from("sleep 0.1"),268 measurements: Measurements::new(vec![269 Measurement {270 time_wall_clock: Time::new::<second>(0.1),271 time_user: Time::new::<second>(0.1),272 time_system: Time::zero(),267- peak_memory_usage: Information::new::<byte>(1024.),273+ memory_peak_resident: Some(Information::new::<byte>(1024.)),274 exit_status: ExitStatus::default(),275 },276 Measurement {277 time_wall_clock: Time::new::<second>(0.2),278 time_user: Time::new::<second>(0.2),279 time_system: Time::zero(),274- peak_memory_usage: Information::new::<byte>(1024.),280+ memory_peak_resident: Some(Information::new::<byte>(1024.)),281 exit_status: ExitStatus::default(),282 },283 Measurement {284 time_wall_clock: Time::new::<second>(0.3),285 time_user: Time::new::<second>(0.3),286 time_system: Time::zero(),281- peak_memory_usage: Information::new::<byte>(1024.),287+ memory_peak_resident: Some(Information::new::<byte>(1024.)),288 exit_status: ExitStatus::default(),289 },290 ]),291 parameters: BTreeMap::new(),43 unmodified lines335 fn test_markup_export_manual_s() {336 let results = [337 BenchmarkResult {338 command: String::from("sleep 2"),333- command_with_unused_parameters: String::from("sleep 2"),339+ name: None,340+ display_name: String::from("sleep 2"),341 measurements: Measurements::new(vec![342 Measurement {343 time_wall_clock: Time::new::<second>(2.01),344 time_user: Time::new::<second>(2.01),345 time_system: Time::zero(),339- peak_memory_usage: Information::new::<byte>(1024.),346+ memory_peak_resident: Some(Information::new::<byte>(1024.)),347 exit_status: ExitStatus::default(),348 },349 Measurement {350 time_wall_clock: Time::new::<second>(2.02),351 time_user: Time::new::<second>(2.02),352 time_system: Time::zero(),346- peak_memory_usage: Information::new::<byte>(1024.),353+ memory_peak_resident: Some(Information::new::<byte>(1024.)),354 exit_status: ExitStatus::default(),355 },356 Measurement {357 time_wall_clock: Time::new::<second>(2.03),358 time_user: Time::new::<second>(2.03),359 time_system: Time::zero(),353- peak_memory_usage: Information::new::<byte>(1024.),360+ memory_peak_resident: Some(Information::new::<byte>(1024.)),361 exit_status: ExitStatus::default(),362 },363 ]),364 parameters: BTreeMap::new(),365 },366 BenchmarkResult {367 command: String::from("sleep 0.1"),361- command_with_unused_parameters: String::from("sleep 0.1"),368+ name: None,369+ display_name: String::from("sleep 0.1"),370 measurements: Measurements::new(vec![371 Measurement {372 time_wall_clock: Time::new::<second>(0.11),373 time_user: Time::new::<second>(0.11),374 time_system: Time::zero(),367- peak_memory_usage: Information::new::<byte>(1024.),375+ memory_peak_resident: Some(Information::new::<byte>(1024.)),376 exit_status: ExitStatus::default(),377 },378 Measurement {379 time_wall_clock: Time::new::<second>(0.12),380 time_user: Time::new::<second>(0.12),381 time_system: Time::zero(),374- peak_memory_usage: Information::new::<byte>(1024.),382+ memory_peak_resident: Some(Information::new::<byte>(1024.)),383 exit_status: ExitStatus::default(),384 },385 Measurement {386 time_wall_clock: Time::new::<second>(0.13),387 time_user: Time::new::<second>(0.13),388 time_system: Time::zero(),381- peak_memory_usage: Information::new::<byte>(1024.),389+ memory_peak_resident: Some(Information::new::<byte>(1024.)),390 exit_status: ExitStatus::default(),391 },392 ]),393 parameters: BTreeMap::new(),40 unmodified linesmodified:src/quantity/mod.rs+45 added-4 removed
1 use std::marker::PhantomData;2 3+use serde::ser::SerializeStruct;4+use serde::Serializer;5+6 use uom::si;7 8 pub use si::f64::{Information, Ratio, Time};9 pub use si::information::{byte, gibibyte, kibibyte, mebibyte, tebibyte};5 unmodified lines15 16 pub mod statistics;17 mod units;18 19+pub trait QuantityInUnit<U> {20+ fn value_in_unit(self) -> f64;21+}22+23+impl<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> QuantityInUnit<U> for Time {24+ fn value_in_unit(self) -> f64 {25+ self.get::<U>()26+ }27+}28+29+impl<U: uom::si::information::Unit + uom::Conversion<f64, T = f64>> QuantityInUnit<U>30+ for Information31+{32+ fn value_in_unit(self) -> f64 {33+ self.get::<U>()34+ }35+}36+37 pub trait FormatQuantity {38 type Unit;39 40 fn suitable_unit(&self) -> Self::Unit;84 unmodified lines125 self.format_with_precision(unit, unit.preferred_precision())126 }127 }128 129+pub fn serialize_time<S>(t: &Time, s: S) -> Result<S::Ok, S::Error>130+where131+ S: Serializer,132+{133+ let mut state = s.serialize_struct("Time", 2)?;134+ state.serialize_field("value", &t.get::<second>())?;135+ state.serialize_field("unit", "second")?;136+ state.end()137+}138+139+pub fn serialize_information<S>(i: &Information, s: S) -> Result<S::Ok, S::Error>140+where141+ S: Serializer,142+{143+ let mut state = s.serialize_struct("Information", 2)?;144+ state.serialize_field("value", &i.get::<byte>())?;145+ state.serialize_field("unit", "byte")?;146+ state.end()147+}148+149 #[test]150 fn test_time() {151 let time = Time::new::<millisecond>(123.4);152 assert_eq!(time.get::<millisecond>(), 123.4);68 unmodified lines221 assert_eq!(time.format(TimeUnit::MilliSecond), "123.4 ms");222 assert_eq!(time.format_auto(), "123.4 ms");223 assert_eq!(time.format(TimeUnit::MicroSecond), "123400.0 µs");224 184- let peak_memory_usage = Information::new::<kibibyte>(8.);185- assert_eq!(peak_memory_usage.format_auto(), "8.0 KiB");186- assert_eq!(peak_memory_usage.format(InformationUnit::Byte), "8192 B");225+ let memory_peak_resident = Information::new::<kibibyte>(8.);226+ assert_eq!(memory_peak_resident.format_auto(), "8.0 KiB");227+ assert_eq!(memory_peak_resident.format(InformationUnit::Byte), "8192 B");228 assert_eq!(188- peak_memory_usage.format(InformationUnit::KibiByte),229+ memory_peak_resident.format(InformationUnit::KibiByte),230 "8.0 KiB"231 );232 }233 11 unmodified linesmodified:src/timer/mod.rs+2 added-2 removed
80 unmodified lines81 // Handle CommandOutputPolicy::Pipe82 discard(output);83 }84 85- let (time_user, time_system, peak_memory_usage, exit_status) = cpu_timer.stop(child)?;85+ let (time_user, time_system, memory_peak_resident, exit_status) = cpu_timer.stop(child)?;86 let time_wall_clock = wallclock_timer.stop();87 88 Ok(Measurement {89 time_wall_clock,90 time_user,91 time_system,92- peak_memory_usage,92+ memory_peak_resident,93 exit_status,94 })95 }modified:src/timer/unix_timer.rs+2 added-2 removed
75 unmodified lines76 pub fn start() -> Self {77 Self {}78 }79 80- pub fn stop(&self, child: Child) -> Result<(Time, Time, Information, ExitStatus)> {80+ pub fn stop(&self, child: Child) -> Result<(Time, Time, Option<Information>, ExitStatus)> {81 let (status, usage) = wait4(child)?;82 Ok((83 usage.time_user,84 usage.time_system,85- usage.memory_usage,85+ Some(usage.memory_usage),86 status,87 ))88 }89 }modified:src/timer/windows_timer.rs+3 added-3 removed
82 unmodified lines83 84 Self { job_object }85 }86 87- pub fn stop(&self, mut child: Child) -> Result<(Time, Time, Information, ExitStatus)> {87+ pub fn stop(&self, mut child: Child) -> Result<(Time, Time, Option<Information>, ExitStatus)> {88 let status = child.wait()?;89 90 let mut job_object_info =91 mem::MaybeUninit::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>::uninit();23 unmodified lines115 // processes no longer associated with the job, in 100-nanosecond ticks."116 let system_time =117 Time::new::<nanosecond>((job_object_info.TotalKernelTime as f64) * 100.0);118 119- Ok((user_time, system_time, Information::zero(), status))119+ Ok((user_time, system_time, None, status))120 } else {121- Ok((Time::zero(), Time::zero(), Information::zero(), status))121+ Ok((Time::zero(), Time::zero(), None, status))122 }123 }124 }125 6 unmodified linesadded:tests/snapshots/integration_tests__json_export_basic.snap+199 added
1+---2+source: tests/integration_tests.rs3+info:4+ program: hyperfine5+ args:6+ - "--debug-mode"7+ - "--style=none"8+ - "--export-json=-"9+ - "--runs=2"10+ - "--warmup=1"11+ - "--reference-name=one second"12+ - "--reference=sleep 1"13+ - "--command-name=sleep 2"14+ - sleep 215+---16+success: true17+exit_code: 018+----- stdout -----19+20+{21+ "schema_version": 2,22+ "metadata": {23+ "hyperfine_version": "[hyperfine_version]",24+ "start_time": "[start_time]",25+ "platform": {26+ "os": "[os]",27+ "architecture": "[architecture]"28+ }29+ },30+ "results": [31+ {32+ "command": "sleep 1",33+ "name": "one second",34+ "measurements": [35+ {36+ "time_wall_clock": {37+ "value": 1.0,38+ "unit": "second"39+ },40+ "time_user": {41+ "value": 0.0,42+ "unit": "second"43+ },44+ "time_system": {45+ "value": 0.0,46+ "unit": "second"47+ },48+ "memory_peak_resident": {49+ "value": 0.0,50+ "unit": "byte"51+ },52+ "exit_code": 053+ },54+ {55+ "time_wall_clock": {56+ "value": 1.0,57+ "unit": "second"58+ },59+ "time_user": {60+ "value": 0.0,61+ "unit": "second"62+ },63+ "time_system": {64+ "value": 0.0,65+ "unit": "second"66+ },67+ "memory_peak_resident": {68+ "value": 0.0,69+ "unit": "byte"70+ },71+ "exit_code": 072+ }73+ ],74+ "is_reference": true,75+ "summary": {76+ "time_wall_clock": {77+ "unit": "second",78+ "count": 2,79+ "mean": 1.0,80+ "stddev": 0.0,81+ "median": 1.0,82+ "min": 1.0,83+ "max": 1.084+ },85+ "time_user": {86+ "unit": "second",87+ "count": 2,88+ "mean": 0.0,89+ "stddev": 0.0,90+ "median": 0.0,91+ "min": 0.0,92+ "max": 0.093+ },94+ "time_system": {95+ "unit": "second",96+ "count": 2,97+ "mean": 0.0,98+ "stddev": 0.0,99+ "median": 0.0,100+ "min": 0.0,101+ "max": 0.0102+ },103+ "memory_peak_resident": {104+ "unit": "byte",105+ "count": 2,106+ "mean": 0.0,107+ "stddev": 0.0,108+ "median": 0.0,109+ "min": 0.0,110+ "max": 0.0111+ }112+ }113+ },114+ {115+ "command": "sleep 2",116+ "measurements": [117+ {118+ "time_wall_clock": {119+ "value": 2.0,120+ "unit": "second"121+ },122+ "time_user": {123+ "value": 0.0,124+ "unit": "second"125+ },126+ "time_system": {127+ "value": 0.0,128+ "unit": "second"129+ },130+ "memory_peak_resident": {131+ "value": 0.0,132+ "unit": "byte"133+ },134+ "exit_code": 0135+ },136+ {137+ "time_wall_clock": {138+ "value": 2.0,139+ "unit": "second"140+ },141+ "time_user": {142+ "value": 0.0,143+ "unit": "second"144+ },145+ "time_system": {146+ "value": 0.0,147+ "unit": "second"148+ },149+ "memory_peak_resident": {150+ "value": 0.0,151+ "unit": "byte"152+ },153+ "exit_code": 0154+ }155+ ],156+ "summary": {157+ "time_wall_clock": {158+ "unit": "second",159+ "count": 2,160+ "mean": 2.0,161+ "stddev": 0.0,162+ "median": 2.0,163+ "min": 2.0,164+ "max": 2.0165+ },166+ "time_user": {167+ "unit": "second",168+ "count": 2,169+ "mean": 0.0,170+ "stddev": 0.0,171+ "median": 0.0,172+ "min": 0.0,173+ "max": 0.0174+ },175+ "time_system": {176+ "unit": "second",177+ "count": 2,178+ "mean": 0.0,179+ "stddev": 0.0,180+ "median": 0.0,181+ "min": 0.0,182+ "max": 0.0183+ },184+ "memory_peak_resident": {185+ "unit": "byte",186+ "count": 2,187+ "mean": 0.0,188+ "stddev": 0.0,189+ "median": 0.0,190+ "min": 0.0,191+ "max": 0.0192+ }193+ }194+ }195+ ]196+}197+198+199+----- stderr -----added:tests/snapshots/integration_tests__json_export_parameterized_with_reference.snap+211 added
1+---2+source: tests/integration_tests.rs3+info:4+ program: hyperfine5+ args:6+ - "--debug-mode"7+ - "--style=none"8+ - "--export-json=-"9+ - "--runs=2"10+ - "-L"11+ - duration12+ - "1,2"13+ - "--command-name=sleep for {duration} seconds"14+ - "--reference=sleep for 2 seconds"15+ - "sleep {duration}"16+---17+success: true18+exit_code: 019+----- stdout -----20+21+{22+ "schema_version": 2,23+ "metadata": {24+ "hyperfine_version": "[hyperfine_version]",25+ "start_time": "[start_time]",26+ "platform": {27+ "os": "[os]",28+ "architecture": "[architecture]"29+ }30+ },31+ "results": [32+ {33+ "command": "sleep 1",34+ "name": "sleep for 1 seconds",35+ "measurements": [36+ {37+ "time_wall_clock": {38+ "value": 1.0,39+ "unit": "second"40+ },41+ "time_user": {42+ "value": 0.0,43+ "unit": "second"44+ },45+ "time_system": {46+ "value": 0.0,47+ "unit": "second"48+ },49+ "memory_peak_resident": {50+ "value": 0.0,51+ "unit": "byte"52+ },53+ "exit_code": 054+ },55+ {56+ "time_wall_clock": {57+ "value": 1.0,58+ "unit": "second"59+ },60+ "time_user": {61+ "value": 0.0,62+ "unit": "second"63+ },64+ "time_system": {65+ "value": 0.0,66+ "unit": "second"67+ },68+ "memory_peak_resident": {69+ "value": 0.0,70+ "unit": "byte"71+ },72+ "exit_code": 073+ }74+ ],75+ "parameters": {76+ "duration": {77+ "value": "1"78+ }79+ },80+ "summary": {81+ "time_wall_clock": {82+ "unit": "second",83+ "count": 2,84+ "mean": 1.0,85+ "stddev": 0.0,86+ "median": 1.0,87+ "min": 1.0,88+ "max": 1.089+ },90+ "time_user": {91+ "unit": "second",92+ "count": 2,93+ "mean": 0.0,94+ "stddev": 0.0,95+ "median": 0.0,96+ "min": 0.0,97+ "max": 0.098+ },99+ "time_system": {100+ "unit": "second",101+ "count": 2,102+ "mean": 0.0,103+ "stddev": 0.0,104+ "median": 0.0,105+ "min": 0.0,106+ "max": 0.0107+ },108+ "memory_peak_resident": {109+ "unit": "byte",110+ "count": 2,111+ "mean": 0.0,112+ "stddev": 0.0,113+ "median": 0.0,114+ "min": 0.0,115+ "max": 0.0116+ }117+ }118+ },119+ {120+ "command": "sleep 2",121+ "name": "sleep for 2 seconds",122+ "measurements": [123+ {124+ "time_wall_clock": {125+ "value": 2.0,126+ "unit": "second"127+ },128+ "time_user": {129+ "value": 0.0,130+ "unit": "second"131+ },132+ "time_system": {133+ "value": 0.0,134+ "unit": "second"135+ },136+ "memory_peak_resident": {137+ "value": 0.0,138+ "unit": "byte"139+ },140+ "exit_code": 0141+ },142+ {143+ "time_wall_clock": {144+ "value": 2.0,145+ "unit": "second"146+ },147+ "time_user": {148+ "value": 0.0,149+ "unit": "second"150+ },151+ "time_system": {152+ "value": 0.0,153+ "unit": "second"154+ },155+ "memory_peak_resident": {156+ "value": 0.0,157+ "unit": "byte"158+ },159+ "exit_code": 0160+ }161+ ],162+ "parameters": {163+ "duration": {164+ "value": "2"165+ }166+ },167+ "is_reference": true,168+ "summary": {169+ "time_wall_clock": {170+ "unit": "second",171+ "count": 2,172+ "mean": 2.0,173+ "stddev": 0.0,174+ "median": 2.0,175+ "min": 2.0,176+ "max": 2.0177+ },178+ "time_user": {179+ "unit": "second",180+ "count": 2,181+ "mean": 0.0,182+ "stddev": 0.0,183+ "median": 0.0,184+ "min": 0.0,185+ "max": 0.0186+ },187+ "time_system": {188+ "unit": "second",189+ "count": 2,190+ "mean": 0.0,191+ "stddev": 0.0,192+ "median": 0.0,193+ "min": 0.0,194+ "max": 0.0195+ },196+ "memory_peak_resident": {197+ "unit": "byte",198+ "count": 2,199+ "mean": 0.0,200+ "stddev": 0.0,201+ "median": 0.0,202+ "min": 0.0,203+ "max": 0.0204+ }205+ }206+ }207+ ]208+}209+210+211+----- stderr -----added:tests/snapshots/integration_tests__json_export_single_run.snap+93 added
1+---2+source: tests/integration_tests.rs3+info:4+ program: hyperfine5+ args:6+ - "--debug-mode"7+ - "--style=none"8+ - "--export-json=-"9+ - "--runs=1"10+ - sleep 111+---12+success: true13+exit_code: 014+----- stdout -----15+16+{17+ "schema_version": 2,18+ "metadata": {19+ "hyperfine_version": "[hyperfine_version]",20+ "start_time": "[start_time]",21+ "platform": {22+ "os": "[os]",23+ "architecture": "[architecture]"24+ }25+ },26+ "results": [27+ {28+ "command": "sleep 1",29+ "measurements": [30+ {31+ "time_wall_clock": {32+ "value": 1.0,33+ "unit": "second"34+ },35+ "time_user": {36+ "value": 0.0,37+ "unit": "second"38+ },39+ "time_system": {40+ "value": 0.0,41+ "unit": "second"42+ },43+ "memory_peak_resident": {44+ "value": 0.0,45+ "unit": "byte"46+ },47+ "exit_code": 048+ }49+ ],50+ "summary": {51+ "time_wall_clock": {52+ "unit": "second",53+ "count": 1,54+ "mean": 1.0,55+ "stddev": null,56+ "median": 1.0,57+ "min": 1.0,58+ "max": 1.059+ },60+ "time_user": {61+ "unit": "second",62+ "count": 1,63+ "mean": 0.0,64+ "stddev": null,65+ "median": 0.0,66+ "min": 0.0,67+ "max": 0.068+ },69+ "time_system": {70+ "unit": "second",71+ "count": 1,72+ "mean": 0.0,73+ "stddev": null,74+ "median": 0.0,75+ "min": 0.0,76+ "max": 0.077+ },78+ "memory_peak_resident": {79+ "unit": "byte",80+ "count": 1,81+ "mean": 0.0,82+ "stddev": null,83+ "median": 0.0,84+ "min": 0.0,85+ "max": 0.086+ }87+ }88+ }89+ ]90+}91+92+93+----- stderr -----modified:tests/integration_tests.rs+55 added-1 removed
22 unmodified lines23 settings.add_filter(r"(?m)[ \t]+$", "");24 settings25 }26 27+fn json_snapshot_settings() -> insta::Settings {28+ let mut settings = snapshot_settings();29+ for field in ["hyperfine_version", "start_time", "os", "architecture"] {30+ settings.add_filter(31+ &format!(r#"("{field}": ")[^"]+(")"#),32+ format!(r#"${{1}}[{field}]$2"#),33+ );34+ }35+ settings36+}37+38 #[test]39 fn runs_successfully() {40 hyperfine()41 .arg("--runs=2")884 unmodified lines926 assert_eq!(results.len(), 3);927 assert_eq!(928 results929 .iter()919- .map(|result| result["parameters"]["delay"].as_str().unwrap())930+ .map(|result| result["parameters"]["delay"]["value"].as_str().unwrap())931 .collect::<Vec<_>>(),932 ["0.2", "0.4", "0.6"]933 );934 }348 unmodified lines1283 "conclude:1",1284 ]1285 );1286 }1287+1288+#[test]1289+fn json_export_basic() {1290+ let _settings = json_snapshot_settings().bind_to_scope();1291+ assert_cmd_snapshot!(hyperfine_debug().args([1292+ "--style=none",1293+ "--export-json=-",1294+ "--runs=2",1295+ "--warmup=1",1296+ "--reference-name=one second",1297+ "--reference=sleep 1",1298+ "--command-name=sleep 2",1299+ "sleep 2",1300+ ]));1301+}1302+1303+#[test]1304+fn json_export_single_run() {1305+ // Make sure that the standard deviation is set to `null`1306+ let _settings = json_snapshot_settings().bind_to_scope();1307+ assert_cmd_snapshot!(hyperfine_debug().args([1308+ "--style=none",1309+ "--export-json=-",1310+ "--runs=1",1311+ "sleep 1",1312+ ]));1313+}1314+1315+#[test]1316+fn json_export_parameterized_with_reference() {1317+ let _settings = json_snapshot_settings().bind_to_scope();1318+ assert_cmd_snapshot!(hyperfine_debug().args([1319+ "--style=none",1320+ "--export-json=-",1321+ "--runs=2",1322+ "-L",1323+ "duration",1324+ "1,2",1325+ "--command-name=sleep for {duration} seconds",1326+ "--reference=sleep for 2 seconds",1327+ "sleep {duration}",1328+ ]));1329+}modified:Cargo.lock+18 added
368 unmodified lines369 source = "registry+https://github.com/rust-lang/crates.io-index"370 checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"371 372 [[package]]373+name = "humantime"374+version = "2.4.0"375+source = "registry+https://github.com/rust-lang/crates.io-index"376+checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15"377+378+[[package]]379 name = "hyperfine"380 version = "1.21.0"381 dependencies = [382 "anyhow",2 unmodified lines385 "clap",386 "clap_complete",387 "colored",388 "csv",389+ "humantime",390 "indicatif",391 "insta",392 "insta-cmd",393 "libc",394 "nix",395 "once_cell",396+ "platform-info",397 "predicates",398 "rand 0.10.3",399 "rust_decimal",400 "serde",138 unmodified lines539 source = "registry+https://github.com/rust-lang/crates.io-index"540 checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"541 542 [[package]]543+name = "platform-info"544+version = "2.2.0"545+source = "registry+https://github.com/rust-lang/crates.io-index"546+checksum = "ba7c3f5af00d3596a148cc80178ac690152b71c283d15a8bcea0cddfea759a36"547+dependencies = [548+ "libc",549+ "windows-sys 0.61.2",550+]551+552+[[package]]553 name = "portable-atomic"554 version = "1.15.0"555 source = "registry+https://github.com/rust-lang/crates.io-index"556 checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"644 unmodified linesmodified:Cargo.toml+2 added
27 unmodified lines28 shell-words = "1.1"29 thiserror = "2.0"30 anyhow = "1.0"31 uom = { version = "0.36.0", default-features = false, features = ["std", "si", "f64"] }32+humantime = "2"33+platform-info = "2.2"34 35 [target.'cfg(not(windows))'.dependencies]36 libc = "0.2"37 48 unmodified linesmodified:README.md+22 added
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 includes the following metrics for each measured run (excluding warmup runs):162+163+- **`time_wall_clock`**: Time from start to finish, including time spent waiting, in seconds.164+165+- **`time_user`**: CPU time spent running the program's code, summed across threads, in seconds.166+167+ - Linux/macOS: Includes child-process time when parents wait for their children to finish.168+ - Windows: Includes the command and its child processes.169+170+- **`time_system`**: CPU time spent running operating-system code for the program, for example171+ to read files, summed across threads, in seconds.172+173+ - Linux/macOS: Includes child-process time when parents wait for their children to finish.174+ - Windows: Includes the command and its child processes.175+176+- **`memory_peak_resident`**: Peak memory held in physical RAM, in bytes.177+178+ - Linux/macOS: Peak resident set size (RSS). This is the largest per-process peak among the179+ command and child processes (whose usage is collected when their parents wait for them),180+ *not the simultaneous total memory of the full process tree*.181+ - Windows: Currently not supported.182+183 The JSON output is useful if you want to analyze the benchmark results in more detail. The184 [`scripts/`](https://github.com/sharkdp/hyperfine/tree/master/scripts) folder includes a lot185 of helpful Python programs to further analyze benchmark results and create helpful186 visualizations, like a histogram of runtimes or a whisker plot to compare190 unmodified lines