Skip to content
Myr

Alternative performance metrics in the terminal (#986)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Peter · committed by GitHub · parent 3b64ea1 · Browse files · 43 files+1872 added−2056 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

43 files+1872 added−2056 removed

  • tests:+319 added−310 removed
  • other:+1553 added−1746 removed

43 files+1872 added−2056 removed

modified:doc/hyperfine.1+43 added-66 removed
13 unmodified lines
14.RB [ \-\-runs15.IR NUM ]16.RB [ \-\-setup17.IR CMD ]18.RB [ \-\-reference19.IR CMD ]20.RB [ \-\-reference\-name21.IR NAME ]18.RB [ \-\-prepare19.IR CMD ]20.RB [ \-\-conclude21.IR CMD ]
11 unmodified lines
33.RB [ \-\-shell34.IR SHELL ]35.RB [ \-\-style36.IR TYPE ]41.RB [ \-\-sort42.IR METHOD ]43.RB [ \-\-time-unit44.IR UNIT ]37.RB [ \-\-metrics38.IR METRIC[:UNIT],...|default|time|all ]39.RB [ \-\-export\-asciidoc40.IR FILE ]41.RB [ \-\-export\-csv42.IR FILE ]
25 unmodified lines
68.RS69* Warmup runs can be executed before the actual benchmark70.RE71.RS78* Cache-clearing commands can be set up before each timing run72* Cache-clearing commands can be set up before each benchmark run73.RE74.RS75* Statistical outlier detection to detect interference from other programs and caching effects76.RE
25 unmodified lines
102\fBhyperfine\fR automatically determines the number of runs.103.HP104\fB\-s\fR, \fB\-\-setup\fR \fICMD...\fP105.IP112Execute \fICMD\fP once before each set of timing runs. This is useful106Execute \fICMD\fP once before each set of benchmark runs. This is useful107for compiling your software with the provided parameters, or to do any108other work that should happen once before a series of benchmark runs,109not every time as would happen with the \fB\-\-prepare\fR option.110.HP117\fB\-\-reference\fR \fICMD\fP118.IP119Use \fICMD\fP as the reference for the relative comparison of results. Without120parameters, benchmark \fICMD\fP as a separate reference command. If this option121is not specified, the fastest command is used as the reference.122With \fB\-\-parameter\-scan\fR or \fB\-\-parameter\-list\fR, select an existing123benchmark by its exact printed name. The name must match exactly one benchmark.124.HP125\fB\-\-reference\-name\fR \fINAME\fP126.IP127Give a meaningful \fINAME\fP to the reference command.128Requires \fB\-\-reference\fR.129Cannot be used with parameterized benchmarks; use \fB\-\-command\-name\fR instead.130.HP111\fB\-p\fR, \fB\-\-prepare\fR \fICMD...\fP112.IP133Execute \fICMD\fP before each timing run. This is useful for clearing disk caches,113Execute \fICMD\fP before each benchmark run. This is useful for clearing disk caches,114for example.115The \fB\-\-prepare\fR option can be specified once for all commands or multiple times,116once for each command. In the latter case, each preparation command will be117run prior to the corresponding benchmark command.118.HP119\fB\-C\fR, \fB\-\-conclude\fR \fICMD...\fP120.IP141Execute \fICMD\fP after each timing run. This is useful for clearing disk caches,121Execute \fICMD\fP after each benchmark run. This is useful for clearing disk caches,122for example.123The \fB\-\-conclude\fR option can be specified once for all commands or multiple times,124once for each command. In the latter case, each conclusion command will be125run after the corresponding benchmark command.
101 unmodified lines
227interactive output without any colors. Set this to 'color' to keep the colors228without any interactive output. Set this to 'none' to disable all the output229of the tool.230.HP251\fB\-\-sort\fR \fIMETHOD\fP231\fB\-\-metrics\fR \fIMETRIC[:UNIT],...|default|time|all\fP232.IP253Specify the sort order of the speed comparison summary and the254exported tables for markup formats (Markdown, AsciiDoc, org\-mode):255.RS256.IP "auto (default)"257the speed comparison will be ordered by time and258the markup tables will be ordered by command (input order).259.IP "command"260order benchmarks in the way they were specified261.IP "mean\-time"262order benchmarks by mean runtime263.RE264.HP265\fB\-u\fR, \fB\-\-time\-unit\fR \fIUNIT\fP233Select the metrics to display, in order, with an optional unit for each.234Default: \fBtime_wall_clock,memory_peak_resident\fR, or \fBtime_wall_clock\fR235on Windows, where peak resident memory is not yet supported.236.IP267Set the time unit to be used. If the option is not given, the time unit is268determined automatically. Possible values:237Use \fBdefault\fR for the platform defaults, \fBtime\fR for238\fBtime_wall_clock,time_cpu,time_user,time_system\fR, or \fBall\fR for all available239metrics in the order listed below.240.IP241Time metrics \fBtime_wall_clock\fR, \fBtime_cpu\fR, \fBtime_user\fR, and \fBtime_system\fR242accept units \fBns\fR, \fBus\fR, \fBms\fR, \fBs\fR, \fBmin\fR, and \fBh\fR.243Peak memory, \fBmemory_peak_resident\fR, accepts \fBB\fR, \fBkB\fR,244\fBMB\fR, \fBGB\fR, \fBTB\fR, \fBKiB\fR, \fBMiB\fR, \fBGiB\fR,245and \fBTiB\fR.246.IP247Counter metrics \fBcpu_cycles\fR, \fBinstructions\fR, \fBcache_references\fR,248\fBcache_misses\fR, and \fBbranch_misses\fR accept \fBcount\fR (unscaled),249\fBk\fR (thousand), \fBM\fR (million), and \fBB\fR (billion).250.IP251If a unit is omitted, terminal and markup output automatically select a suitable252unit.253.RS270.IP "microsecond"271Aliases: µs, us, microseconds.272.IP "millisecond"273Aliases: ms, milliseconds.274.IP "second"275Aliases: s, seconds.276.IP "minute"277Aliases: min, minutes.278.IP "hour"279Aliases: h, hours.254Example:255.RS256\fBhyperfine\fR \fB\-\-metrics\fR memory_peak_resident:MiB,time_wall_clock:ms,instructions:B './baseline' './candidate'257.RE281.IP282This option affects the standard output as well as all export formats283except for CSV and JSON.258.RE259.HP260\fB\-\-export\-asciidoc\fR \fIFILE\fP 261.IP287Export the timing summary statistics as an AsciiDoc table to the given \fIFILE\fP.288The output time unit can be changed using the \fB\-\-time\-unit\fR option.262Export the primary metric's summary statistics as an AsciiDoc table to the given263\fIFILE\fP. Use its selected unit, or choose a unit automatically when omitted.264.HP265\fB\-\-export\-csv\fR \fIFILE\fP266.IP292Export the timing summary statistics as CSV to the given \fIFILE\fP. If you need the293timing results for each individual run, use the JSON export format.294The output time unit is always seconds.267Export the primary metric's summary statistics as CSV to the given \fIFILE\fP,268identifying the metric and unit explicitly. Use the explicitly selected unit,269or the base unit (seconds, bytes, or unscaled counts) when omitted.270.HP271\fB\-\-export\-json\fR \fIFILE\fP272.IP298Export the timing summary statistics and timings of individual runs as JSON to299the given \fIFILE\fP. The output time unit is always seconds.273Export summary statistics and individual samples for all collected metrics as274JSON to the given \fIFILE\fP. Include the primary metric, and always use base275units (seconds, bytes, or unscaled counts), regardless of display settings.276.HP277\fB\-\-export\-markdown\fR \fIFILE\fP278.IP303Export the timing summary statistics as a Markdown table to the given \fIFILE\fP.304The output time unit can be changed using the \fB\-\-time\-unit\fR option.279Export the primary metric's summary statistics as a Markdown table to the given280\fIFILE\fP. Use its selected unit, or choose a unit automatically when omitted.281.HP282\fB\-\-export\-orgmode\fR \fIFILE\fP283.IP308Export the timing summary statistics as an Emacs org\-mode table to the309given \fIFILE\fP. The output time unit can be changed using the \fB\-\-time\-unit\fR option.284Export the primary metric's summary statistics as an Emacs org\-mode table to285the given \fIFILE\fP. Use its selected unit, or choose a unit automatically286when omitted.287.HP288\fB\-\-show\-output\fR289.IP290Print the stdout and stderr of the benchmark instead of suppressing it. This
100 unmodified lines
modified:scripts/advanced_statistics.py+27 added-45 removed
5 unmodified lines
6# ]7# ///89import argparse10import json11from enum import Enum1011import numpy as np1213from plot_utils import METRICS, add_metric_argument, load_results1416class Unit(Enum):17 SECOND = 118 MILLISECOND = 21920 def factor(self):21 match self:22 case Unit.SECOND:23 return 124 case Unit.MILLISECOND:25 return 1e32627 def __str__(self):28 match self:29 case Unit.SECOND:30 return "s"31 case Unit.MILLISECOND:32 return "ms"333415parser = argparse.ArgumentParser()16parser.add_argument("file", help="JSON file with benchmark results")17add_metric_argument(parser)18parser.add_argument(19 "--time-unit",39 help="The unit of time.",40 default="second",41 action="store",20 help="Display unit for time metrics (default: second).",21 choices=["second", "millisecond"],43 dest="unit",22)23args = parser.parse_args()2447unit = Unit.MILLISECOND if args.unit == "millisecond" else Unit.SECOND48unit_str = str(unit)25metric, [results] = load_results(parser, [args.file], args.metric)26description = METRICS[metric]27unit, scale = description.unit, description.scale28if args.time_unit is not None:29 if not metric.startswith("time_"):30 parser.error("--time-unit can only be used with a time metric")31 if args.time_unit == "millisecond":32 unit, scale = "ms", 0.0013350with open(args.file) as f:51 results = json.load(f)["results"]3435def format_value(value):36 suffix = f" {unit}" if unit else ""37 return f"{value:.3f}{suffix}"383940print(f"Metric: {description.label}\n")41for result in results:54 summary = result["summary"]["time_wall_clock"]55 ts = [m["time_wall_clock"]["value"] * unit.factor() for m in result["measurements"]]42 summary = result["summary"][metric]43 values = [m[metric]["value"] / scale for m in result["measurements"]]4457 p05 = np.percentile(ts, 5)58 p25 = np.percentile(ts, 25)59 p75 = np.percentile(ts, 75)60 p95 = np.percentile(ts, 95)45 p05, p25, p75, p95 = np.percentile(values, [5, 25, 75, 95])4647 iqr = p75 - p254849 print(f"Command '{result.get('name', result['command'])}'")50 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}")51 for statistic in ["mean", "stddev", "median", "min", "max"]:52 value = summary[statistic]53 formatted = "N/A" if value is None else format_value(value / scale)54 print(f" {statistic + ':':<8}{formatted:>8}")55 print()56 print(" percentiles:")76 print(f" P_05 .. P_95: {p05:.3f} {unit_str} .. {p95:.3f} {unit_str}")57 print(f" P_05 .. P_95: {format_value(p05)} .. {format_value(p95)}")58 print(78 f" P_25 .. P_75: {p25:.3f} {unit_str} .. {p75:.3f} {unit_str} (IQR = {iqr:.3f} {unit_str})"59 f" P_25 .. P_75: {format_value(p25)} .. {format_value(p75)}"60 f" (IQR = {format_value(iqr)})"61 )62 print()
modified:scripts/plot_benchmark_comparison.py+6 added-9 removed
12 unmodified lines
13Note all the input files must contain results for all commands.14"""1516import argparse17import json17import pathlib1819import matplotlib.pyplot as plt20import numpy as np2123from plot_utils import METRICS, add_metric_argument, validate_metric22from plot_utils import METRICS, add_metric_argument, load_results2324parser = argparse.ArgumentParser(description=__doc__)25add_metric_argument(parser)26parser.add_argument(
5 unmodified lines
32)33parser.add_argument("-o", "--output", help="Save image to the given filename")3435args = parser.parse_args()37metric_label, metric_scale = METRICS[args.metric]36metric, datasets = load_results(parser, args.files, args.metric)37metric_info = METRICS[metric]3839commands = None40data = []41inputs = []
2 unmodified lines
44 assert len(args.files) == len(args.benchmark_names), (45 "Number of benchmark names must match the number of input files."46 )4748for i, filename in enumerate(args.files):49 with open(filename) as f:50 results = json.load(f)["results"]51 validate_metric(parser, results, args.metric)48for i, (filename, results) in enumerate(zip(args.files, datasets)):49 benchmark_commands = [b.get("name", b["command"]) for b in results]50 if commands is None:51 commands = benchmark_commands52 else:53 assert commands == benchmark_commands, (54 f"Unexpected commands in {filename}: {benchmark_commands}, expected: {commands}"55 )59 data.append([b["summary"][args.metric]["mean"] / metric_scale for b in results])56 data.append([b["summary"][metric]["mean"] / metric_info.scale for b in results])57 if args.benchmark_names:58 inputs.append(args.benchmark_names[i])59 else:60 inputs.append(filename.stem)
14 unmodified lines
7576if args.title:77 plt.title(args.title)78plt.xlabel("Benchmark")82plt.ylabel(metric_label)79plt.ylabel(metric_info.axis_label)80plt.legend(title="Command")8182if args.output:83 plt.savefig(args.output)
2 unmodified lines
modified:scripts/plot_histogram.py+5 added-9 removed
9 unmodified lines
1011"""This program shows `hyperfine` benchmark results as a histogram."""1213import argparse14import json1415import matplotlib.pyplot as plt16import numpy as np1719from plot_utils import METRICS, add_metric_argument, validate_metric18from plot_utils import METRICS, add_metric_argument, load_results1920parser = argparse.ArgumentParser(description=__doc__)21add_metric_argument(parser)22parser.add_argument("file", help="JSON file with benchmark results")
45 unmodified lines
68 action="store_true",69)7071args = parser.parse_args()73metric_label, metric_scale = METRICS[args.metric]72metric, [results] = load_results(parser, [args.file], args.metric)73metric_info = METRICS[metric]7475with open(args.file) as f:76 results = json.load(f)["results"]77validate_metric(parser, results, args.metric)7875if args.labels:76 labels = args.labels.split(",")77else:78 labels = [b.get("name", b["command"]) for b in results]79all_values = [84 [m[args.metric]["value"] / metric_scale for m in b["measurements"]] for b in results80 [m[metric]["value"] / metric_info.scale for m in b["measurements"]] for b in results81]8283value_min = (84 args.value_min
23 unmodified lines
108 shadow=True,109 prop={"size": 10, "family": ["Source Code Pro", "Fira Mono", "Courier New"]},110)111116plt.xlabel(metric_label)112plt.xlabel(metric_info.axis_label)113if args.title:114 plt.title(args.title)115116if args.log_count:
8 unmodified lines
modified:scripts/plot_parametrized.py+8 added-12 removed
9 unmodified lines
10"""This program shows parametrized `hyperfine` benchmark results as an11errorbar plot."""1213import argparse14import json14import sys1516import matplotlib.pyplot as plt1719from plot_utils import METRICS, add_metric_argument, validate_metric18from plot_utils import METRICS, add_metric_argument, load_results1920parser = argparse.ArgumentParser(description=__doc__)21add_metric_argument(parser)22parser.add_argument("file", help="JSON file with benchmark results", nargs="+")
18 unmodified lines
41)42parser.add_argument("-o", "--output", help="Save image to the given filename.")4344args = parser.parse_args()46metric_label, metric_scale = METRICS[args.metric]45metric, datasets = load_results(parser, args.file, args.metric)46metric_info = METRICS[metric]47if args.parameter_name is not None:48 sys.stderr.write(49 "warning: --parameter-name is deprecated; names are inferred from "50 "benchmark results\n"
32 unmodified lines
838485parameter_name = None8687for filename in args.file:88 with open(filename) as f:89 results = json.load(f)["results"]90 validate_metric(parser, results, args.metric)9187for results in datasets:88 (this_parameter_name, parameter_values) = extract_parameters(results)89 if parameter_name is not None and this_parameter_name != parameter_name:90 die(91 f"files must all have the same parameter name, but found {parameter_name!r} vs. {this_parameter_name!r}"92 )93 parameter_name = this_parameter_name9499 summaries = [b["summary"][args.metric] for b in results]100 means = [s["mean"] / metric_scale for s in summaries]95 summaries = [b["summary"][metric] for b in results]96 means = [s["mean"] / metric_info.scale for s in summaries]97 stddevs = [102 s["stddev"] / metric_scale if s["stddev"] is not None else float("nan")98 s["stddev"] / metric_info.scale if s["stddev"] is not None else float("nan")99 for s in summaries100 ]101102 plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2)103104plt.xlabel(parameter_name)109plt.ylabel(metric_label)105plt.ylabel(metric_info.axis_label)106107if args.log_y:108 plt.yscale("log")109else:
12 unmodified lines
modified:scripts/plot_progression.py+5 added-9 removed
12 unmodified lines
13thermal throttling and similar effects.14"""1516import argparse17import json1718import matplotlib.pyplot as plt19import numpy as np2022from plot_utils import METRICS, add_metric_argument, validate_metric21from plot_utils import METRICS, add_metric_argument, load_results222324def moving_average(values, num_runs):25 values_padded = np.pad(
22 unmodified lines
48)495051args = parser.parse_args()53metric_label, metric_scale = METRICS[args.metric]52metric, [results] = load_results(parser, [args.file], args.metric)53metric_info = METRICS[metric]5455with open(args.file) as f:56 results = json.load(f)["results"]57validate_metric(parser, results, args.metric)5855for result in results:56 label = result.get("name", result["command"])61 values = [m[args.metric]["value"] / metric_scale for m in result["measurements"]]57 values = [m[metric]["value"] / metric_info.scale for m in result["measurements"]]58 num = len(values)59 nums = range(num)6061 plt.scatter(x=nums, y=values, marker=".")
19 unmodified lines
81 if not args.no_moving_average:82 legend.append("moving average")83plt.legend(legend)8489plt.ylabel(metric_label)85plt.ylabel(metric_info.axis_label)8687if args.output:88 plt.savefig(args.output)89else:
1 unmodified line
modified:scripts/plot_utils.py+54 added-12 removed
1"""Shared metric options for the plotting scripts."""1"""Shared metric selection and units for analysis and plotting scripts."""23import json4from typing import NamedTuple567class Metric(NamedTuple):8 label: str9 unit: str = ""10 scale: float = 11112 @property13 def axis_label(self):14 return f"{self.label} [{self.unit}]" if self.unit else self.label151617METRICS = {4 "time_wall_clock": ("Time [s]", 1),5 "time_user": ("User CPU time [s]", 1),6 "time_system": ("System CPU time [s]", 1),7 "memory_peak_resident": ("Peak resident memory [MiB]", 1024**2),8 "cpu_cycles": ("CPU cycles", 1),9 "instructions": ("Completed CPU instructions", 1),10 "cache_references": ("Cache references", 1),11 "cache_misses": ("Cache misses", 1),12 "branch_misses": ("Mispredicted branches", 1),18 "time_wall_clock": Metric("Wall-clock time", "s"),19 "time_cpu": Metric("Total CPU time", "s"),20 "time_user": Metric("User CPU time", "s"),21 "time_system": Metric("System CPU time", "s"),22 "memory_peak_resident": Metric("Peak resident memory", "MiB", 1024**2),23 "cpu_cycles": Metric("CPU cycles"),24 "instructions": Metric("Completed CPU instructions"),25 "cache_references": Metric("Cache references"),26 "cache_misses": Metric("Cache misses"),27 "branch_misses": Metric("Mispredicted branches"),28}293031def add_metric_argument(parser):32 parser.add_argument(33 "--metric",34 choices=METRICS,20 default="time_wall_clock",21 help="Metric to plot (default: time_wall_clock). "35 help="Metric to analyze (default: primary_metric from the JSON export, "36 "or time_wall_clock if unspecified). "37 "Times are in seconds; memory is in MiB; hardware counters are unscaled counts.",38 )3940
3 unmodified lines
44 parser.error(45 f"metric {metric!r} is unavailable for "46 f"{result.get('name', result['command'])!r}"47 )484950def load_results(parser, filenames, metric=None):51 exports = []52 for filename in filenames:53 with open(filename, encoding="utf-8") as f:54 export = json.load(f)55 if not export["results"]:56 parser.error(f"no benchmark results in {filename}")57 exports.append(export)5859 if metric is None:60 primary_metrics = {61 export.get("primary_metric", "time_wall_clock") for export in exports62 }63 if len(primary_metrics) != 1:64 parser.error(65 "input files use different primary metrics; select one with --metric"66 )67 metric = primary_metrics.pop()68 if metric not in METRICS:69 parser.error(f"unknown metric {metric!r}; select one with --metric")7071 results = [export["results"] for export in exports]72 for benchmarks in results:73 validate_metric(parser, benchmarks, metric)74 return metric, results
modified:scripts/plot_whisker.py+6 added-10 removed
14 unmodified lines
15 of the data. Flier points are those past the end of the whiskers.16"""1718import argparse19import json1920import matplotlib.pyplot as plt2123from plot_utils import METRICS, add_metric_argument, validate_metric22from plot_utils import METRICS, add_metric_argument, load_results2324parser = argparse.ArgumentParser(description=__doc__)25add_metric_argument(parser)26parser.add_argument("file", help="JSON file with benchmark results")
4 unmodified lines
31)32parser.add_argument("-o", "--output", help="Save image to the given filename.")3334args = parser.parse_args()36metric_label, metric_scale = METRICS[args.metric]35metric, [results] = load_results(parser, [args.file], args.metric)36metric_info = METRICS[metric]3738with open(args.file, encoding="utf-8") as f:39 results = json.load(f)["results"]40validate_metric(parser, results, args.metric)4138if args.labels:39 labels = args.labels.split(",")40else:41 labels = [b.get("name", b["command"]) for b in results]42values = [47 [m[args.metric]["value"] / metric_scale for m in b["measurements"]] for b in results43 [m[metric]["value"] / metric_info.scale for m in b["measurements"]] for b in results44]4546if args.sort_by == "median":51 medians = [b["summary"][args.metric]["median"] for b in results]47 medians = [b["summary"][metric]["median"] for b in results]48 indices = sorted(range(len(labels)), key=lambda k: medians[k])49 labels = [labels[i] for i in indices]50 values = [values[i] for i in indices]51
7 unmodified lines
5960if args.title:61 plt.title(args.title)62plt.legend(handles=boxplot["boxes"], labels=labels, loc="best", fontsize="medium")67plt.ylabel(metric_label)63plt.ylabel(metric_info.axis_label)64plt.ylim(0, None)65plt.xticks(list(range(1, len(labels) + 1)), labels, rotation=45)66if args.output:67 plt.savefig(args.output)
2 unmodified lines
modified:scripts/README.md+1 added-3 removed
5 unmodified lines
6hyperfine 'sleep 0.020' 'sleep 0.021' 'sleep 0.022' --export-json sleep.json7uv run plot_whisker.py sleep.json8```910All plotting scripts accept `--metric` to select a metric. Hardware counters11(`cpu_cycles`, `instructions`, `cache_references`, `cache_misses`, and `branch_misses`)12are plotted as unscaled counts when available in the JSON export. For example:10All plotting and analysis scripts use the JSON export's `primary_metric` by default.1112```bash13uv run plot_histogram.py benchmark.json --metric instructions14```
9 unmodified lines
modified:scripts/welch_ttest.py+15 added-10 removed
5 unmodified lines
6# ]7# ///89"""This script performs Welch's t-test on a JSON export file with two10benchmark results to test for a difference in their population mean runtimes."""10benchmark results to test for a difference in their population means."""1112import argparse13import json14import sys13import math1415from scipy import stats1617from plot_utils import METRICS, add_metric_argument, load_results1819parser = argparse.ArgumentParser(description=__doc__)20parser.add_argument("file", help="JSON file with two benchmark results")21add_metric_argument(parser)22args = parser.parse_args()2322with open(args.file) as f:23 results = json.load(f)["results"]24metric, [results] = load_results(parser, [args.file], args.metric)2526if len(results) != 2:26 print("The input file has to contain exactly two benchmarks")27 sys.exit(1)27 parser.error("the input file must contain exactly two benchmarks")2829a, b = (x.get("name", x["command"]) for x in results[:2])30X, Y = ([m["time_wall_clock"]["value"] for m in x["measurements"]] for x in results[:2])30X, Y = ([m[metric]["value"] for m in x["measurements"]] for x in results[:2])31if min(len(X), len(Y)) < 2:32 parser.error("Welch's t-test requires at least two measurements per benchmark")3334print(f"Metric: {METRICS[metric].label}")35print(f"Command 1: {a}")36print(f"Command 2: {b}\n")3738t, p = stats.ttest_ind(X, Y, equal_var=False)39if not math.isfinite(p):40 parser.error("Welch's t-test is undefined for these measurements")41th = 0.0542dispose = p < th43print(f"t = {t:.3}, p = {p:.3}")44print()4546if dispose:47 print(43 f"A statistically significant difference in mean runtime was detected (p < {th})."48 f"A statistically significant difference in mean value was detected (p < {th})."49 )50else:51 print(47 f"No statistically significant difference in mean runtime was detected (p >= {th})."52 f"No statistically significant difference in mean value was detected (p >= {th})."53 )
modified:src/benchmark/benchmark_result.rs-6 removed
1 unmodified line
23use serde::Serialize;45use crate::benchmark::measurement::Measurements;6use crate::quantity::Time;67/// Parameter value8#[derive(Debug, Default, Clone, Serialize, PartialEq)]9pub struct Parameter {
35 unmodified lines
45impl BenchmarkResult {46 pub fn get_name(&self) -> &str {47 self.name.as_deref().unwrap_or(&self.command)48 }5051 /// The average wall clock time52 pub fn mean_wall_clock_time(&self) -> Time {53 self.measurements.time_wall_clock_mean()54 }49}
modified:src/benchmark/executor.rs+3 added
218 unmodified lines
219 measurement.time_user =220 ensure_non_negative(measurement.time_user - spawning_time.time_user);221 measurement.time_system =222 ensure_non_negative(measurement.time_system - spawning_time.time_system);223 measurement.time_cpu = measurement.time_user + measurement.time_system;224 }225226 Ok(measurement)227 }
50 unmodified lines
278 }279280 self.shell_spawning_time = Some(Measurement {281 time_wall_clock: measurements.time_wall_clock_mean(),282 time_cpu: measurements.time_user_mean() + measurements.time_system_mean(),283 time_user: measurements.time_user_mean(),284 time_system: measurements.time_system_mean(),285 memory_peak_resident: None,286 hardware_counters: Default::default(),
51 unmodified lines
338 };339340 Ok(Measurement {341 time_wall_clock: Self::extract_time(command.get_command_line()),342 time_cpu: Time::zero(),343 time_user: Time::zero(),344 time_system: Time::zero(),345 memory_peak_resident: Some(Information::zero()),346 hardware_counters: Default::default(),
23 unmodified lines
modified:src/benchmark/measurement.rs+39 added-30 removed
1use std::process::ExitStatus;23use serde::Serialize;45use crate::quantity::statistics::{max, mean, median, min, modified_zscores, standard_deviation};5use crate::metric::Metric;6use crate::quantity::statistics::{mean, modified_zscores_f64};7use crate::quantity::{serialize_information, serialize_time, Information, Time};8use crate::util::exit_code::extract_exit_code;910fn serialize_exit_status<S>(exit_status: &ExitStatus, serializer: S) -> Result<S::Ok, S::Error>
66 unmodified lines
77 /// Elapsed wall clock time (real time)78 #[serde(serialize_with = "serialize_time")]79 pub time_wall_clock: Time,8081 /// Total CPU time (user and kernel mode)82 #[serde(serialize_with = "serialize_time")]83 pub time_cpu: Time,8485 /// Time spent in user mode86 #[serde(serialize_with = "serialize_time")]87 pub time_user: Time,88
46 unmodified lines
135 pub fn time_wall_clock_mean(&self) -> Time {136 mean(self.wall_clock_times())137 }138134 /// The standard deviation of all wall clock times. Not available if only one run has been performed135 pub fn stddev(&self) -> Option<Time> {136 let times: Vec<_> = self.wall_clock_times().collect(); // TODO: Avoid collecting137138 if times.len() < 2 {139 None140 } else {141 Some(standard_deviation(times))142 }139 /// Compute modified Z-scores for a metric validated to be available in every run.140 pub fn modified_zscores(&self, metric: Metric) -> Vec<f64> {141 let values: Vec<_> = self142 .measurements143 .iter()144 .map(|m| metric.value(m).expect("Validated metric is available"))145 .collect();146 modified_zscores_f64(&values)147 }148145 /// The median wall clock time146 pub fn median(&self) -> Time {147 median(self.wall_clock_times())148 }149150 /// The minimum wall clock time151 pub fn min(&self) -> Time {152 min(self.wall_clock_times())153 }154155 /// The maximum wall clock time156 pub fn max(&self) -> Time {157 max(self.wall_clock_times())158 }159160 /// Compute modified Z-scores for the wall clock times161 pub fn modified_zscores(&self) -> Vec<f64> {162 modified_zscores(&self.wall_clock_times().collect::<Vec<_>>())163 }164149 /// The average user time150 pub fn time_user_mean(&self) -> Time {151 mean(self.measurements.iter().map(|m| m.time_user))152 }
2 unmodified lines
155 pub fn time_system_mean(&self) -> Time {156 mean(self.measurements.iter().map(|m| m.time_system))157 }158}159160#[cfg(test)]161mod tests {162 use super::*;163 use crate::outlier_detection::OUTLIER_THRESHOLD;164 use crate::quantity::{byte, second};165166 #[test]167 fn outliers_follow_the_selected_metric() {168 let measurements = Measurements::new(169 [(1.0, 100.0), (1.0, 1.0), (1.0, 1.0), (100.0, 1.0)]170 .iter()171 .copied()172 .map(|(time, memory)| Measurement {173 time_wall_clock: Time::new::<second>(time),174 memory_peak_resident: Some(Information::new::<byte>(memory)),175 ..Measurement::default()176 })177 .collect(),178 );179180 assert!(measurements.modified_zscores(Metric::TimeWallClock)[0] < OUTLIER_THRESHOLD);181 assert!(measurements.modified_zscores(Metric::MemoryPeakResident)[0] > OUTLIER_THRESHOLD);182 }183}
modified:src/benchmark/mod.rs+66 added-93 removed
1pub mod benchmark_result;2pub mod executor;3pub mod measurement;4pub mod relative_speed;4pub mod scheduler;56use std::cmp;7use std::io::{self, Write};
8 unmodified lines
16};17use crate::outlier_detection::OUTLIER_THRESHOLD;18use crate::output::console_writeln;19use crate::output::progress_bar::{21 finish_initial_measurement, get_progress_bar, start_initial_measurement,20 finish_initial_measurement, get_progress_bar, set_benchmark_header, start_initial_measurement,21};22use crate::output::report;23use crate::output::warnings::{OutlierWarningOptions, Warnings};24use crate::parameter::ParameterNameAndValue;25use crate::quantity::{self, const_time_from_seconds, FormatQuantity, Time, Zero};25use crate::quantity::{self, const_time_from_seconds, Time, Zero};26use benchmark_result::BenchmarkResult;2728use anyhow::{anyhow, Result};28use anyhow::{anyhow, ensure, Result};29use colored::*;3031use self::executor::Executor;32
121 unmodified lines
154155 self.run_intermediate_command(command, error_output, output_policy, iteration)156 }157158 /// Run the benchmark for a single command159 pub fn run(&self) -> Result<BenchmarkResult> {160 if self.options.output_style != OutputStyleOption::Disabled {161 console_writeln!(162 io::stdout(),163 "{}{}: {}",164 "Benchmark ".bold(),165 (self.number + 1).to_string().bold(),166 self.command.get_name_with_unused_parameters(),167 )?;158 fn validate_measurement(&self, measurement: &Measurement) -> Result<()> {159 if self.options.skip_unavailable_metrics {160 return Ok(());161 }162 for selection in &self.options.metrics {163 ensure!(selection.metric.value(measurement).is_some(),164 "Metric '{}' is unavailable for '{}'. Check platform support and hardware-counter permissions.",165 selection.metric.name(), self.command.get_command_line());166 }167 Ok(())168 }169170 /// Run the benchmark for a single command171 pub fn run(&self, reference: Option<&BenchmarkResult>) -> Result<BenchmarkResult> {172 let mut measurements = Measurements::default();171 let mut all_succeeded = true;173174 let output_policy = &self.options.command_output_policies[self.number];175176 let preparation_command = self.options.preparation_command.as_ref().map(|values| {
36 unmodified lines
213 };214215 self.run_setup_command(self.command.get_parameters().iter().cloned(), output_policy)?;216217 let progress_header = format!(218 "{}: {}",219 format!("Benchmark {}", self.number + 1).bold(),220 self.command221 .get_name_with_unused_parameters()222 .white()223 .bold()224 );225226 // Warmup phase227 if self.options.warmup_count > 0 {228 let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {229 Some(get_progress_bar(
4 unmodified lines
234 } else {235 None236 };237238 if let Some(bar) = &progress_bar {239 set_benchmark_header(bar, progress_header.clone());240 }241242 for i in 0..self.options.warmup_count {243 let warmup_iteration = BenchmarkIteration::Warmup(i);244 let _ = run_preparation_command(warmup_iteration)?;245 let _ = self.executor.run_command_and_measure(
26 unmodified lines
272 } else {273 None274 };275276 if let Some(bar) = &progress_bar {277 set_benchmark_header(bar, progress_header);278 }279280 let benchmark_iteration = BenchmarkIteration::Benchmark(0);281 let preparation_result = run_preparation_command(benchmark_iteration)?;282 let preparation_overhead = preparation_result.map_or(Time::zero(), |res| {283 res.time_wall_clock + self.executor.time_overhead()
8 unmodified lines
292 benchmark_iteration,293 None,294 output_policy,295 )?;296 self.validate_measurement(&measurement)?;278 let success = measurement.exit_status.success();297 let mut all_succeeded = measurement.exit_status.success();298299 if let Some(bar) = progress_bar.as_ref() {281 let time_unit = self282 .options283 .time_unit284 .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 );300 let primary = self.options.metrics[0];301 let value = primary.metric.value(&measurement).unwrap();302 let estimate = primary.display_unit(value).format(value);303 finish_initial_measurement(bar, format!("Current estimate: {}", estimate.green()));304 }305306 let conclusion_result = run_conclusion_command(benchmark_iteration)?;307 let conclusion_overhead = conclusion_result.map_or(Time::zero(), |res| {
21 unmodified lines
329330 let count_remaining = count - 1;331332 // Save the first result333 let primary = self.options.metrics[0];334 let mut primary_total = primary.metric.value(&measurement).unwrap();335 measurements.push(measurement);336321 all_succeeded = all_succeeded && success;322337 // Re-configure the progress bar338 if let Some(bar) = progress_bar.as_ref() {339 bar.set_length(count);340 bar.inc(1);
2 unmodified lines
343 // Gather statistics (perform the actual benchmark)344 for i in 0..count_remaining {345 let benchmark_iteration = BenchmarkIteration::Benchmark(i + 1);346333 let msg = {334 let t_wall_clock_mean = measurements.time_wall_clock_mean();335 let time_unit = self336 .options337 .time_unit338 .unwrap_or(t_wall_clock_mean.suitable_unit());339 let mean = t_wall_clock_mean.format(time_unit);340 format!("Current estimate: {}", mean.to_string().green())341 };342347 if let Some(bar) = progress_bar.as_ref() {348 let mean = primary_total / measurements.len() as f64;344 bar.set_message(msg.to_owned())349 bar.set_message(format!(350 "Current estimate: {}",351 primary.display_unit(mean).format(mean).green()352 ));353 }354355 run_preparation_command(benchmark_iteration)?;356
2 unmodified lines
359 benchmark_iteration,360 None,361 output_policy,362 )?;363 self.validate_measurement(&measurement)?;364 let success = measurement.exit_status.success();365 primary_total += primary.metric.value(&measurement).unwrap();366 measurements.push(measurement);367368 all_succeeded = all_succeeded && success;369
7 unmodified lines
377 if let Some(bar) = progress_bar.as_ref() {378 bar.finish_and_clear()379 }380371 // Formatting and console output372 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());381382 let user_str = measurements.time_user_mean().format(time_unit);383 let system_str = measurements.time_system_mean().format(time_unit);384381 if self.options.output_style != OutputStyleOption::Disabled {386 let mut stdout = io::stdout().lock();387 if measurements.len() == 1 {388 console_writeln!(389 stdout,390 " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",391 "abs".green().bold(),392 mean_str.green().bold(),393 " ", // alignment394 user_str.blue(),395 system_str.blue()396 )?;397 } else {398 let stddev_str = measurements.stddev().unwrap().format(time_unit);399400 console_writeln!(401 stdout,402 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",403 "mean".green().bold(),404 "σ".green(),405 mean_str.green().bold(),406 stddev_str.green(),407 user_str.blue(),408 system_str.blue()409 )?;410411 console_writeln!(412 stdout,413 " Range ({} … {}): {:>8} … {:>8} {}",414 "min".cyan(),415 "max".purple(),416 min_str.cyan(),417 max_str.purple(),418 num_str.dimmed()419 )?;420 }382 report::print(383 self.number,384 &self.command.get_name_with_unused_parameters(),385 &measurements,386 &self.options.metrics,387 self.options.skip_unavailable_metrics,388 reference,389 )?;390 }391392 // Warnings393 let mut warnings = vec![];394395 // Check execution time396 if self397 .options398 .metrics399 .iter()400 .any(|m| m.metric == crate::metric::Metric::TimeWallClock)427 if matches!(self.options.executor_kind, ExecutorKind::Shell(_))401 && matches!(self.options.executor_kind, ExecutorKind::Shell(_))402 && measurements403 .wall_clock_times()404 .any(|t| t < MIN_EXECUTION_TIME)405 {
5 unmodified lines
411 warnings.push(Warnings::NonZeroExitCode);412 }413414 // Run outlier detection441 let scores = measurements.modified_zscores();415 let scores = measurements.modified_zscores(primary.metric);416417 let outlier_warning_options = OutlierWarningOptions {418 warmup_in_use: self.options.warmup_count > 0,419 prepare_in_use: self
5 unmodified lines
425 > 0,426 };427428 if scores[0] > OUTLIER_THRESHOLD {455 warnings.push(Warnings::SlowInitialRun(456 measurements.wall_clock_times().next().unwrap(),429 warnings.push(Warnings::InitialRunOutlier(430 primary,431 primary.metric.value(&measurements.measurements[0]).unwrap(),432 outlier_warning_options,433 ));459 } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {460 warnings.push(Warnings::OutliersDetected(outlier_warning_options));434 }435436 if !warnings.is_empty() {437 let mut stderr = io::stderr().lock();
38 unmodified lines
deleted:src/benchmark/relative_speed.rs-237 removed
1use std::cmp::Ordering;23use super::benchmark_result::BenchmarkResult;4use crate::{5 options::SortOrder,6 quantity::{self, Ratio, Time, Zero},7};89#[derive(Debug)]10pub struct BenchmarkResultWithRelativeSpeed<'a> {11 pub result: &'a BenchmarkResult,12 pub relative_speed: f64,13 pub relative_speed_stddev: Option<f64>,14 pub is_reference: bool,15 // Less means faster16 pub relative_ordering: Ordering,17}1819impl BenchmarkResultWithRelativeSpeed<'_> {20 pub fn reference_label(&self) -> &'static str {21 if self.is_reference {22 " (reference)"23 } else {24 match self.relative_ordering {25 Ordering::Less => " (faster)",26 Ordering::Equal => " (same speed)",27 Ordering::Greater => " (slower)",28 }29 }30 }31}3233pub fn compare_mean_time(l: &BenchmarkResult, r: &BenchmarkResult) -> Ordering {34 l.mean_wall_clock_time()35 .partial_cmp(&r.mean_wall_clock_time())36 .unwrap_or(Ordering::Equal)37}3839pub fn fastest_of(results: &[BenchmarkResult]) -> &BenchmarkResult {40 results41 .iter()42 .min_by(|&l, &r| compare_mean_time(l, r))43 .expect("at least one benchmark result")44}4546fn compute_relative_speeds<'a>(47 results: &'a [BenchmarkResult],48 reference: &'a BenchmarkResult,49 sort_order: SortOrder,50) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> {51 let mut results: Vec<_> = results52 .iter()53 .map(|result| {54 // Separate benchmarks can have identical names and measurements.55 let is_reference = std::ptr::eq(result, reference);56 let relative_ordering = compare_mean_time(result, reference);5758 if result.mean_wall_clock_time() == Time::zero()59 || reference.mean_wall_clock_time() == Time::zero()60 {61 return BenchmarkResultWithRelativeSpeed {62 result,63 relative_speed: if is_reference { 1.0 } else { f64::INFINITY },64 relative_speed_stddev: None,65 is_reference,66 relative_ordering,67 };68 }6970 let ratio = match relative_ordering {71 Ordering::Less => reference.mean_wall_clock_time() / result.mean_wall_clock_time(),72 Ordering::Equal => Ratio::new::<quantity::ratio>(1.0),73 Ordering::Greater => {74 result.mean_wall_clock_time() / reference.mean_wall_clock_time()75 }76 };7778 // https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas79 // Covariance assumed to be 0, i.e. variables are assumed to be independent80 let ratio_stddev = match (81 result.measurements.stddev(),82 reference.measurements.stddev(),83 ) {84 (Some(result_stddev), Some(reference_stddev)) => Some(85 ratio86 * ((result_stddev / result.mean_wall_clock_time())87 .powi(uom::typenum::P2::new())88 + (reference_stddev / reference.mean_wall_clock_time())89 .powi(uom::typenum::P2::new()))90 .sqrt(),91 ),92 _ => None,93 };9495 BenchmarkResultWithRelativeSpeed {96 result,97 relative_speed: ratio.get::<quantity::ratio>(),98 relative_speed_stddev: ratio_stddev.map(|r| r.get::<quantity::ratio>()),99 is_reference,100 relative_ordering,101 }102 })103 .collect();104105 match sort_order {106 SortOrder::Command => {}107 SortOrder::MeanTime => {108 results.sort_unstable_by(|r1, r2| compare_mean_time(r1.result, r2.result));109 }110 }111112 results113}114115pub fn compute_with_check_from_reference<'a>(116 results: &'a [BenchmarkResult],117 reference: &'a BenchmarkResult,118 sort_order: SortOrder,119) -> Option<Vec<BenchmarkResultWithRelativeSpeed<'a>>> {120 if fastest_of(results).mean_wall_clock_time() == Time::zero()121 || reference.mean_wall_clock_time() == Time::zero()122 {123 return None;124 }125126 Some(compute_relative_speeds(results, reference, sort_order))127}128129pub fn compute_with_check(130 results: &[BenchmarkResult],131 sort_order: SortOrder,132) -> Option<Vec<BenchmarkResultWithRelativeSpeed<'_>>> {133 let fastest = fastest_of(results);134135 if fastest.mean_wall_clock_time() == Time::zero() {136 return None;137 }138139 Some(compute_relative_speeds(results, fastest, sort_order))140}141142/// Compute relative speeds against the given reference, or the fastest result.143pub fn compute<'a>(144 results: &'a [BenchmarkResult],145 sort_order: SortOrder,146 reference: Option<&'a BenchmarkResult>,147) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> {148 let reference = reference.unwrap_or_else(|| fastest_of(results));149 compute_relative_speeds(results, reference, sort_order)150}151152#[cfg(test)]153fn create_result(name: &str, mean: f64) -> BenchmarkResult {154 use std::collections::BTreeMap;155156 use crate::benchmark::measurement::{Measurement, Measurements};157 use crate::quantity::second;158159 BenchmarkResult {160 command: 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),167 ..Default::default()168 }],169 },170 parameters: BTreeMap::new(),171 }172}173174#[test]175fn test_compute_relative_speed() {176 use approx::assert_relative_eq;177178 let results = vec![179 create_result("cmd1", 3.0),180 create_result("cmd2", 2.0),181 create_result("cmd3", 5.0),182 ];183184 let annotated_results = compute_with_check(&results, SortOrder::Command).unwrap();185186 assert_relative_eq!(1.5, annotated_results[0].relative_speed);187 assert_relative_eq!(1.0, annotated_results[1].relative_speed);188 assert_relative_eq!(2.5, annotated_results[2].relative_speed);189}190191#[test]192fn test_compute_relative_speed_with_reference() {193 use approx::assert_relative_eq;194195 let results = vec![create_result("cmd2", 2.0), create_result("cmd3", 5.0)];196 let reference = create_result("cmd2", 4.0);197198 let annotated_results =199 compute_with_check_from_reference(&results, &reference, SortOrder::Command).unwrap();200201 assert_relative_eq!(2.0, annotated_results[0].relative_speed);202 assert_relative_eq!(1.25, annotated_results[1].relative_speed);203}204205#[test]206fn test_compute_relative_speed_for_zero_times() {207 let results = vec![create_result("cmd1", 1.0), create_result("cmd2", 0.0)];208209 let annotated_results = compute_with_check(&results, SortOrder::Command);210211 assert!(annotated_results.is_none());212}213214#[test]215fn reference_identity_distinguishes_equal_results() {216 let results = vec![create_result("same", 1.0), create_result("same", 1.0)];217 let entries = compute_relative_speeds(&results, &results[0], SortOrder::Command);218219 assert!(entries[0].is_reference);220 assert!(!entries[1].is_reference);221}222223#[test]224fn 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 {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);232233 let entries = compute_relative_speeds(&results, &results[1], SortOrder::Command);234 assert_eq!(entries[0].relative_speed, f64::INFINITY);235 assert_eq!(entries[0].relative_speed_stddev, None);236 assert_eq!(entries[1].relative_speed, 1.0);237}
modified:src/benchmark/scheduler.rs+24 added-130 removed
1use super::benchmark_result::BenchmarkResult;2use super::executor::{Executor, MockExecutor, RawExecutor, ShellExecutor};3use super::{relative_speed, Benchmark};4use colored::*;5use std::cmp::Ordering;6use std::io::{self, Write};3use super::Benchmark;48use crate::command::{Command, Commands};5use crate::command::Commands;6use crate::export::ExportManager;10use crate::options::{ExecutorKind, Options, OutputStyleOption, SortOrder};11use crate::output::console_writeln;7use crate::options::{ExecutorKind, Options};89use anyhow::Result;1011pub struct Scheduler<'a> {
23 unmodified lines
35 ExecutorKind::Mock(ref shell) => Box::new(MockExecutor::new(shell.clone())),36 ExecutorKind::Shell(ref shell) => Box::new(ShellExecutor::new(shell, self.options)),37 };3843 let reference = self44 .options45 .reference_command46 .as_ref()47 .map(|cmd| Command::new(self.options.reference_name.as_deref(), cmd));4839 executor.calibrate()?;4051 for (number, cmd) in reference.iter().chain(self.commands.iter()).enumerate() {52 self.results53 .push(Benchmark::new(number, cmd, self.options, &*executor).run()?);41 for (number, cmd) in self.commands.iter().enumerate() {42 self.results.push(43 Benchmark::new(number, cmd, self.options, &*executor).run(self.results.first())?,44 );4546 // We export results after each individual benchmark, because47 // we would risk losing them if a later benchmark fails.57 self.export_manager58 .write_results(&self.results, true, self.options.reference_index)?;48 self.export_manager.write_results(&self.results, true)?;49 }5051 Ok(())52 }5364 pub fn print_relative_speed_comparison(&self) -> Result<()> {65 if self.options.output_style == OutputStyleOption::Disabled {66 return Ok(());67 }6869 if self.results.len() < 2 {70 return Ok(());71 }7273 let reference = self74 .options75 .reference_index76 .map(|index| &self.results[index])77 .unwrap_or_else(|| relative_speed::fastest_of(&self.results));7879 if let Some(annotated_results) = relative_speed::compute_with_check_from_reference(80 &self.results,81 reference,82 self.options.sort_order_speed_comparison,83 ) {84 let mut stdout = io::stdout().lock();85 match self.options.sort_order_speed_comparison {86 SortOrder::MeanTime => {87 console_writeln!(stdout, "{}", "Summary".bold())?;8889 let reference = annotated_results.iter().find(|r| r.is_reference).unwrap();90 let others = annotated_results.iter().filter(|r| !r.is_reference);9192 console_writeln!(stdout, " {} ran", reference.result.display_name.cyan())?;9394 for item in others {95 let stddev = if let Some(stddev) = item.relative_speed_stddev {96 format!(" ± {}", format!("{:.2}", stddev).green())97 } else {98 "".into()99 };100 let comparator = match item.relative_ordering {101 Ordering::Less => format!(102 "{}{} times slower than",103 format!("{:8.2}", item.relative_speed).bold().green(),104 stddev105 ),106 Ordering::Greater => format!(107 "{}{} times faster than",108 format!("{:8.2}", item.relative_speed).bold().green(),109 stddev110 ),111 Ordering::Equal => format!(112 " As fast ({}{}) as",113 format!("{:.2}", item.relative_speed).bold().green(),114 stddev115 ),116 };117 console_writeln!(118 stdout,119 "{} {}",120 comparator,121 &item.result.display_name.magenta()122 )?;123 }124 }125 SortOrder::Command => {126 console_writeln!(stdout, "{}", "Relative speed comparison".bold())?;127128 for item in annotated_results {129 let relationship = if self.options.reference_index.is_some() {130 item.reference_label()131 } else {132 ""133 };134 console_writeln!(135 stdout,136 " {}{} {}{}",137 format!("{:10.2}", item.relative_speed).bold().green(),138 if item.is_reference {139 " ".into()140 } else if let Some(stddev) = item.relative_speed_stddev {141 format!(" ± {}", format!("{stddev:5.2}").green())142 } else {143 " ".into()144 },145 item.result.display_name,146 relationship,147 )?;148 }149 }150 }151 } else {152 console_writeln!(153 io::stderr(),154 "{}: The benchmark comparison could not be computed as some benchmark times are zero. \155 This could be caused by background interference during the initial calibration phase \156 of hyperfine, in combination with very fast commands (faster than a few milliseconds). \157 Try to re-run the benchmark on a quiet system. If you did not do so already, try the \158 --shell=none/-N option. If it does not help either, you command is most likely too fast \159 to be accurately benchmarked by hyperfine.",160 "Note".bold().red()161 )?;162 }163164 Ok(())165 }16654 pub fn final_export(&self) -> Result<()> {168 self.export_manager169 .write_results(&self.results, false, self.options.reference_index)55 self.export_manager.write_results(&self.results, false)56 }57}5859#[cfg(test)]
8 unmodified lines
6869 assert_eq!(options.executor_kind, ExecutorKind::Mock(None));7071 let commands = Commands::from_cli_arguments(&cli_arguments)?;186 let export_manager = ExportManager::from_cli_arguments(187 &cli_arguments,188 options.time_unit,189 options.sort_order_exports,190 )?;72 let export_manager = ExportManager::from_cli_arguments(&cli_arguments, options.metrics[0])?;7374 options.validate_against_command_list(&commands)?;7576 let mut scheduler = Scheduler::new(&commands, &options, &export_manager);
3 unmodified lines
80}8182#[test]83fn scheduler_basic() -> Result<()> {202 insta::assert_yaml_snapshot!(generate_results(&["--runs=2", "sleep 0.123", "sleep 0.456"])?, @r#"84 insta::assert_yaml_snapshot!(generate_results(&["--runs=2", "sleep 0.123", "sleep 0.456"])?, @"85 - command: sleep 0.12386 measurements:87 - time_wall_clock:88 value: 0.12389 unit: second90 time_cpu:91 value: 092 unit: second93 time_user:94 value: 095 unit: second96 time_system:
5 unmodified lines
102 exit_code: 0103 - time_wall_clock:104 value: 0.123105 unit: second106 time_cpu:107 value: 0108 unit: second109 time_user:110 value: 0111 unit: second112 time_system:
7 unmodified lines
120 measurements:121 - time_wall_clock:122 value: 0.456123 unit: second124 time_cpu:125 value: 0126 unit: second127 time_user:128 value: 0129 unit: second130 time_system:
5 unmodified lines
136 exit_code: 0137 - time_wall_clock:138 value: 0.456139 unit: second140 time_cpu:141 value: 0142 unit: second143 time_user:144 value: 0145 unit: second146 time_system:
2 unmodified lines
149 memory_peak_resident:150 value: 0151 unit: byte152 exit_code: 0259 "#);153 ");154155 Ok(())156}
modified:src/export/asciidoc.rs+11 added-2 removed
22 unmodified lines
23 "|===\n".to_string()24 }2526 fn table_row(&self, cells: &[&str]) -> String {27 format!("\n| {} \n", cells.join(" \n| "))27 let mut row = String::from("\n");28 for cell in cells {29 row.push('|');30 if !cell.is_empty() {31 row.push(' ');32 row.push_str(cell);33 }34 row.push('\n');35 }36 row37 }3839 fn table_divider(&self, _cell_aligmnents: &[Alignment]) -> String {40 "".to_string()
10 unmodified lines
51 let exporter = AsciidocExporter::default();52 let data = vec!["a", "b", "c"];5354 let actual = exporter.table_row(&data);46 let expect = "\n| a \n| b \n| c \n";55 let expect = "\n| a\n| b\n| c\n";5657 assert_eq!(expect, actual);58}59
17 unmodified lines
modified:src/export/csv.rs+81 added-53 removed
1use std::borrow::Cow;21use csv::WriterBuilder;23use super::Exporter;4use crate::benchmark::benchmark_result::BenchmarkResult;7use crate::options::SortOrder;8use crate::quantity::{FormatQuantity, TimeUnit};5use crate::metric::MetricSelection;610use anyhow::Result;7use anyhow::{Context, Result};89#[derive(Default)]10pub struct CsvExporter {}1112impl Exporter for CsvExporter {16 fn serialize(17 &self,18 results: &[BenchmarkResult],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;24 const CSV_PRECISION: usize = 6;2513 fn serialize(&self, results: &[BenchmarkResult], primary: MetricSelection) -> Result<Vec<u8>> {14 // CSV never chooses units automatically: an omitted suffix means base units.15 let unit = primary.csv_unit();16 let mut writer = WriterBuilder::new().from_writer(vec![]);2728 {29 let mut headers: Vec<Cow<[u8]>> = [30 // The list of times and exit codes cannot be exported to the CSV file - omit them.31 "command", "mean", "stddev", "median", "user", "system", "min", "max",32 ]33 .iter()34 .map(|x| Cow::Borrowed(x.as_bytes()))35 .collect();36 if let Some(res) = results.first() {37 for param_name in res.parameters.keys() {38 headers.push(Cow::Owned(format!("parameter_{param_name}").into_bytes()));39 }40 }41 writer.write_record(headers)?;17 let mut headers: Vec<String> = [18 "command", "metric", "unit", "mean", "stddev", "median", "min", "max",19 ]20 .iter()21 .copied()22 .map(str::to_owned)23 .collect();24 if let Some(result) = results.first() {25 headers.extend(26 result27 .parameters28 .keys()29 .map(|name| format!("parameter_{name}")),30 );31 }32 writer.write_record(headers)?;3344 for res in results {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(),50 res.measurements.time_user_mean(),51 res.measurements.time_system_mean(),52 res.measurements.min(),53 res.measurements.max(),54 ] {55 fields.push(Cow::Owned(56 f.format_with_precision(CSV_UNIT, CSV_PRECISION)57 .into_bytes(),58 ))59 }60 for v in res.parameters.values() {61 fields.push(Cow::Borrowed(v.value.as_bytes()))62 }34 for result in results {35 let stats = primary36 .metric37 .summarize(&result.measurements)38 .with_context(|| {39 format!(40 "Metric '{}' is unavailable for '{}'",41 primary.metric.name(),42 result.get_name()43 )44 })?;45 let mut fields = vec![46 result.get_name().to_owned(),47 primary.metric.name().to_owned(),48 unit.symbol.to_owned(),49 ];50 // Preserve numeric precision rather than using rounded display values.51 fields.extend(52 [53 Some(stats.mean),54 stats.stddev,55 Some(stats.median),56 Some(stats.min),57 Some(stats.max),58 ]59 .map(|value| {60 value61 .map(|value| (value / unit.scale).to_string())62 .unwrap_or_default()63 }),64 );65 fields.extend(66 result67 .parameters68 .values()69 .map(|parameter| parameter.value.clone()),70 );71 writer.write_record(fields)?;72 }7374 Ok(writer.into_inner()?)
18 unmodified lines
93 display_name: String::from("command_a"),94 measurements: Measurements::new(vec![95 Measurement {96 time_wall_clock: Time::new::<second>(7.0),97 time_cpu: Time::new::<second>(7.0),98 time_user: Time::new::<second>(7.0),99 time_system: Time::zero(),100 memory_peak_resident: Some(Information::new::<byte>(1024.)),101 hardware_counters: Default::default(),102 exit_status: ExitStatus::default(),103 },104 Measurement {105 time_wall_clock: Time::new::<second>(8.0),106 time_cpu: Time::new::<second>(8.0),107 time_user: Time::new::<second>(8.0),108 time_system: Time::zero(),109 memory_peak_resident: Some(Information::new::<byte>(1024.)),110 hardware_counters: Default::default(),111 exit_status: ExitStatus::default(),112 },113 Measurement {114 time_wall_clock: Time::new::<second>(12.0),115 time_cpu: Time::new::<second>(12.0),116 time_user: Time::new::<second>(12.0),117 time_system: Time::zero(),118 memory_peak_resident: Some(Information::new::<byte>(1024.)),119 hardware_counters: Default::default(),
23 unmodified lines
143 display_name: String::from("command_b"),144 measurements: Measurements::new(vec![145 Measurement {146 time_wall_clock: Time::new::<second>(17.0),147 time_cpu: Time::new::<second>(17.0),148 time_user: Time::new::<second>(17.0),149 time_system: Time::zero(),150 memory_peak_resident: Some(Information::new::<byte>(1024.)),151 hardware_counters: Default::default(),152 exit_status: ExitStatus::default(),153 },154 Measurement {155 time_wall_clock: Time::new::<second>(18.0),156 time_cpu: Time::new::<second>(18.0),157 time_user: Time::new::<second>(18.0),158 time_system: Time::zero(),159 memory_peak_resident: Some(Information::new::<byte>(1024.)),160 hardware_counters: Default::default(),161 exit_status: ExitStatus::default(),162 },163 Measurement {164 time_wall_clock: Time::new::<second>(19.0),165 time_cpu: Time::new::<second>(19.0),166 time_user: Time::new::<second>(19.0),167 time_system: Time::zero(),168 memory_peak_resident: Some(Information::new::<byte>(1024.)),169 hardware_counters: Default::default(),
20 unmodified lines
190 ];191192 let actual = String::from_utf8(193 exporter180 .serialize(&results, Some(TimeUnit::Second), SortOrder::Command, None)194 .serialize(&results, MetricSelection::default())195 .unwrap(),196 )197 .unwrap();198199 insta::assert_snapshot!(actual, @r#"186 command,mean,stddev,median,user,system,min,max,parameter_bar,parameter_foo187 command_a,9.000000,2.645751,8.000000,9.000000,0.000000,7.000000,12.000000,two,one188 command_b,18.000000,1.000000,18.000000,18.000000,0.000000,17.000000,19.000000,seven,one200 command,metric,unit,mean,stddev,median,min,max,parameter_bar,parameter_foo201 command_a,time_wall_clock,s,9,2.6457513110645907,8,7,12,two,one202 command_b,time_wall_clock,s,18,1,18,17,19,seven,one203 "#);204205 for (selection, unit, mean) in [206 ("memory_peak_resident", "B", "1024"),207 ("memory_peak_resident:KiB", "KiB", "1"),208 ] {209 let output = exporter210 .serialize(&results, MetricSelection::parse_list(selection).unwrap()[0])211 .unwrap();212 let mut reader = csv::Reader::from_reader(output.as_slice());213 let row = reader.records().next().unwrap().unwrap();214 assert_eq!(&row[1], "memory_peak_resident");215 assert_eq!(&row[2], unit);216 assert_eq!(&row[3], mean);217 }218}
modified:src/export/json.rs+33 added-178 removed
1use std::ops::{Add, AddAssign, Div};1use std::collections::BTreeMap;23use serde::*;3use serde::Serialize;4use serde_json::to_vec_pretty;56use super::Exporter;7use crate::benchmark::benchmark_result::BenchmarkResult;8use crate::benchmark::measurement::Measurements;9use crate::options::SortOrder;10use crate::quantity::statistics::{max, mean, median, min, standard_deviation, UnsafeRawValue};11use crate::quantity::{byte, ratio, second, QuantityInUnit, Ratio, TimeUnit, Zero};8use crate::metric::{Metric, MetricSelection, Stats};910use anyhow::Result;1112mod metadata;
4 unmodified lines
17#[derive(Serialize)]18struct HyperfineSummary<'a> {19 schema_version: u32,20 metadata: &'a Metadata,21 primary_metric: &'static str,22 results: Vec<JsonBenchmarkResult<'a>>,23}2425#[derive(Serialize)]26struct JsonBenchmarkResult<'a> {27 #[serde(flatten)]28 result: &'a BenchmarkResult,31 #[serde(skip_serializing_if = "std::ops::Not::not")]32 is_reference: bool,33 summary: BenchmarkSummary,29 summary: BTreeMap<&'static str, StatisticalSummary>,30}3132#[derive(Serialize)]37struct 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 #[serde(skip_serializing_if = "Option::is_none")]44 cpu_cycles: Option<StatisticalSummary>,45 #[serde(skip_serializing_if = "Option::is_none")]46 instructions: Option<StatisticalSummary>,47 #[serde(skip_serializing_if = "Option::is_none")]48 cache_references: Option<StatisticalSummary>,49 #[serde(skip_serializing_if = "Option::is_none")]50 cache_misses: Option<StatisticalSummary>,51 #[serde(skip_serializing_if = "Option::is_none")]52 branch_misses: Option<StatisticalSummary>,53}5455impl BenchmarkSummary {56 fn from_measurements(measurements: &Measurements) -> Self {57 let values = &measurements.measurements;58 Self {59 time_wall_clock: StatisticalSummary::from_values(60 values.iter().map(|m| Some(m.time_wall_clock)),61 Some(second),62 )63 .expect("Benchmarks have at least one measurement"),64 time_user: StatisticalSummary::from_values(65 values.iter().map(|m| Some(m.time_user)),66 Some(second),67 )68 .expect("Benchmarks have at least one measurement"),69 time_system: StatisticalSummary::from_values(70 values.iter().map(|m| Some(m.time_system)),71 Some(second),72 )73 .expect("Benchmarks have at least one measurement"),74 memory_peak_resident: StatisticalSummary::from_values(75 values76 .iter()77 .filter_map(|m| m.memory_peak_resident)78 .map(Some),79 Some(byte),80 ),81 cpu_cycles: StatisticalSummary::from_values(82 values.iter().map(|m| {83 m.hardware_counters84 .cpu_cycles85 .map(|v| Ratio::new::<ratio>(v as f64))86 }),87 None::<ratio>,88 ),89 instructions: StatisticalSummary::from_values(90 values.iter().map(|m| {91 m.hardware_counters92 .instructions93 .map(|v| Ratio::new::<ratio>(v as f64))94 }),95 None::<ratio>,96 ),97 cache_references: StatisticalSummary::from_values(98 values.iter().map(|m| {99 m.hardware_counters100 .cache_references101 .map(|v| Ratio::new::<ratio>(v as f64))102 }),103 None::<ratio>,104 ),105 cache_misses: StatisticalSummary::from_values(106 values.iter().map(|m| {107 m.hardware_counters108 .cache_misses109 .map(|v| Ratio::new::<ratio>(v as f64))110 }),111 None::<ratio>,112 ),113 branch_misses: StatisticalSummary::from_values(114 values.iter().map(|m| {115 m.hardware_counters116 .branch_misses117 .map(|v| Ratio::new::<ratio>(v as f64))118 }),119 None::<ratio>,120 ),121 }122 }123}124125#[derive(Serialize)]33struct StatisticalSummary {34 #[serde(skip_serializing_if = "Option::is_none")]35 unit: Option<&'static str>,36 count: usize,
4 unmodified lines
41 max: f64,42}4344impl StatisticalSummary {138 fn from_values<Q, P, U>(139 values: impl IntoIterator<Item = Option<Q>>,140 unit: Option<U>,141 ) -> Option<Self>142 where143 Q: Copy144 + PartialOrd145 + Add<Output = Q>146 + AddAssign147 + Zero148 + Div<Ratio, Output = P>149 + UnsafeRawValue150 + QuantityInUnit<U>,151 P: Into<Q>,152 U: uom::si::Unit,153 {154 // Only summarize a metric when it is available for every supplied measurement.155 let values: Vec<_> = values.into_iter().collect::<Option<_>>()?;156 if values.is_empty() {157 return None;45 fn new(metric: Metric, stats: Stats) -> Self {46 Self {47 unit: match metric.base_unit().symbol {48 "s" => Some("second"),49 "B" => Some("byte"),50 _ => None,51 },52 count: stats.count,53 mean: stats.mean,54 stddev: stats.stddev,55 median: stats.median,56 min: stats.min,57 max: stats.max,58 }159 Some(Self {160 unit: unit.map(|_| U::singular()),161 count: values.len(),162 mean: mean(values.iter().copied()).value_in_unit(),163 stddev: (values.len() > 1)164 .then(|| standard_deviation(values.iter().copied()).value_in_unit()),165 median: median(values.iter().copied()).value_in_unit(),166 min: min(values.iter().copied()).value_in_unit(),167 max: max(values.iter().copied()).value_in_unit(),168 })59 }60}6162#[derive(Default)]
1 unmodified line
64 metadata: Metadata,65}6667impl Exporter for JsonExporter {178 fn serialize(179 &self,180 results: &[BenchmarkResult],181 _time_unit: Option<TimeUnit>,182 _sort_order: SortOrder,183 reference_index: Option<usize>,184 ) -> Result<Vec<u8>> {68 fn serialize(&self, results: &[BenchmarkResult], primary: MetricSelection) -> Result<Vec<u8>> {69 let mut output = to_vec_pretty(&HyperfineSummary {70 schema_version: JSON_SCHEMA_VERSION,71 metadata: &self.metadata,72 primary_metric: primary.metric.name(),73 results: results74 .iter()190 .enumerate()191 .map(|(index, result)| JsonBenchmarkResult {75 .map(|result| JsonBenchmarkResult {76 result,193 is_reference: reference_index == Some(index),194 summary: BenchmarkSummary::from_measurements(&result.measurements),77 summary: Metric::ALL78 .iter()79 .copied()80 .filter_map(|metric| {81 metric.summarize(&result.measurements).map(|stats| {82 (metric.name(), StatisticalSummary::new(metric, stats))83 })84 })85 .collect(),86 })87 .collect(),197 });198 if let Ok(ref mut content) = output {199 content.push(b'\n');200 }201202 Ok(output?)88 })?;89 output.push(b'\n');90 Ok(output)91 }92}205206#[test]207fn test_statistical_summary_unit_conversion() {208 use crate::quantity::{kibibyte, millisecond, Information, Time};209210 let time = StatisticalSummary::from_values(211 [Time::new::<second>(1.0), Time::new::<second>(3.0)].map(Some),212 Some(millisecond),213 )214 .unwrap();215 let information = StatisticalSummary::from_values(216 [217 Information::new::<byte>(1024.0),218 Information::new::<byte>(3072.0),219 ]220 .map(Some),221 Some(kibibyte),222 )223 .unwrap();224225 for (summary, unit, scale) in [226 (time, "millisecond", 1000.0),227 (information, "kibibyte", 1.0),228 ] {229 assert_eq!(summary.unit, Some(unit));230 assert_eq!(summary.count, 2);231 approx::assert_relative_eq!(summary.mean, 2.0 * scale);232 approx::assert_relative_eq!(summary.median, 2.0 * scale);233 approx::assert_relative_eq!(summary.min, scale);234 approx::assert_relative_eq!(summary.max, 3.0 * scale);235 approx::assert_relative_eq!(summary.stddev.unwrap(), 2.0_f64.sqrt() * scale);236 }237}
modified:src/export/markup.rs+61 added-101 removed
1use crate::benchmark::relative_speed::BenchmarkResultWithRelativeSpeed;2use crate::benchmark::{benchmark_result::BenchmarkResult, relative_speed};3use crate::options::SortOrder;4use crate::quantity::{FormatQuantity, IsUnit, Time, TimeUnit, Zero};1use crate::benchmark::benchmark_result::BenchmarkResult;2use crate::metric::{MetricSelection, Stats, Unit};34use super::Exporter;7use anyhow::Result;8use std::cmp::Ordering;5use anyhow::{Context, Result};67pub enum Alignment {8 Left,9 Right,
1 unmodified line
1112pub trait MarkupExporter {13 fn table_results(14 &self,18 entries: &[BenchmarkResultWithRelativeSpeed],19 time_unit: TimeUnit,20 reference_pending: bool,21 explicit_reference: bool,15 results: &[BenchmarkResult],16 summaries: &[Stats],17 primary: MetricSelection,18 unit: Unit,19 ) -> String {23 // prepare table header strings24 let notation = format!("[{}]", time_unit.short_name());20 let notation = format!("[{}]", unit.symbol);2526 // prepare table cells alignment21 let cells_alignment = [22 Alignment::Left,23 Alignment::Right,24 Alignment::Right,31 Alignment::Right,32 Alignment::Right,25 Alignment::Left,26 ];3435 // emit table header format27 let mut table = self.table_header(&cells_alignment);3738 // emit table header data28 table.push_str(&self.table_row(&[29 "Command",41 &format!("Mean {notation}"),42 &format!("Min {notation}"),43 &format!("Max {notation}"),44 "Relative",30 &format!("Mean {} {notation}", primary.metric.label()),31 "Change",32 "Factor",33 ]));4647 // emit horizontal line34 table.push_str(&self.table_divider(&cells_alignment));3550 for entry in entries {51 let result = &entry.result;52 // prepare data row strings53 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))36 for (index, (result, stats)) in results.iter().zip(summaries).enumerate() {37 let command = result.display_name.replace('|', "\\|");38 let mean = unit.format_value(stats.mean);39 let stddev = stats40 .stddev41 .map(|value| format!(" ± {}", unit.format_value(value)))42 .unwrap_or_default();43 let change = if index == 0 {44 String::new()45 } else {58 "".into()46 stats.format_change_from(&summaries[0])47 };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::Equal67 && result.mean_wall_clock_time() == Time::zero());68 let relative = if relative_unavailable {69 "N/A".to_string()48 let factor = if index == 0 {49 String::new()50 } else {71 let stddev = match (entry.is_reference, entry.relative_speed_stddev) {72 (false, Some(stddev)) => format!(" ± {stddev:.2}"),73 _ => String::new(),74 };75 let label = if explicit_reference {76 entry.reference_label()77 } else {78 ""79 };80 format!("{:.2}{stddev}{label}", entry.relative_speed)51 stats.format_factor_from(&summaries[0], primary.metric)52 };8283 // prepare table row entries53 table.push_str(&self.table_row(&[85 &self.command(&cmd_str),86 &format!("{mean_str}{stddev_str}"),87 &min_str,88 &max_str,89 &relative,90 ]))54 &self.command(&command),55 &format!("{mean}{stddev}"),56 &change,57 &factor,58 ]));59 }9293 // emit table footer format60 table.push_str(&self.table_footer(&cells_alignment));9561 table62 }6364 fn table_row(&self, cells: &[&str]) -> String;65101 fn table_divider(&self, cell_aligmnents: &[Alignment]) -> String;66 fn table_divider(&self, cell_alignments: &[Alignment]) -> String;67103 fn table_header(&self, _cell_aligmnents: &[Alignment]) -> String {104 "".to_string()68 fn table_header(&self, _cell_alignments: &[Alignment]) -> String {69 String::new()70 }71107 fn table_footer(&self, _cell_aligmnents: &[Alignment]) -> String {108 "".to_string()72 fn table_footer(&self, _cell_alignments: &[Alignment]) -> String {73 String::new()74 }75111 fn command(&self, size: &str) -> String;76 fn command(&self, command: &str) -> String;77}78114fn determine_unit_from_results(results: &[BenchmarkResult]) -> TimeUnit {115 if let Some(first_result) = results.first() {116 // Use the first BenchmarkResult entry to determine the unit for all entries.117 first_result.mean_wall_clock_time().suitable_unit()118 } else {119 // Default to `Second`.120 TimeUnit::Second121 }122}12379impl<T: MarkupExporter> Exporter for T {125 fn serialize(126 &self,127 results: &[BenchmarkResult],128 time_unit: Option<TimeUnit>,129 sort_order: SortOrder,130 reference_index: Option<usize>,131 ) -> Result<Vec<u8>> {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(137 results,138 sort_order,139 reference_index.and_then(|i| results.get(i)),140 );141142 let table =143 self.table_results(&entries, unit, reference_pending, reference_index.is_some());144 Ok(table.as_bytes().to_vec())80 fn serialize(&self, results: &[BenchmarkResult], primary: MetricSelection) -> Result<Vec<u8>> {81 let stats: Vec<_> = results82 .iter()83 .map(|result| {84 primary85 .metric86 .summarize(&result.measurements)87 .with_context(|| {88 format!(89 "Metric '{}' is unavailable for '{}'",90 primary.metric.name(),91 result.get_name()92 )93 })94 })95 .collect::<Result<_>>()?;96 // Use one common unit, avoiding an unscaled column if the reference is zero.97 let mean = stats98 .iter()99 .find(|stats| stats.mean != 0.0)100 .map_or(0.0, |stats| stats.mean);101 let unit = primary.display_unit(mean);102 Ok(self103 .table_results(results, &stats, primary, unit)104 .into_bytes())105 }106}
modified:src/export/mod.rs+7 added-30 removed
15 unmodified lines
16use self::markdown::MarkdownExporter;17use self::orgmode::OrgmodeExporter;1819use crate::benchmark::benchmark_result::BenchmarkResult;20use crate::options::SortOrder;20use crate::metric::MetricSelection;21use crate::output::console_writeln;22use crate::quantity::TimeUnit;2223use anyhow::{Context, Result};24use clap::ArgMatches;25
18 unmodified lines
4445/// Interface for different exporters.46trait Exporter {47 /// Export the given entries in the serialized form.49 fn serialize(50 &self,51 results: &[BenchmarkResult],52 time_unit: Option<TimeUnit>,53 sort_order: SortOrder,54 reference_index: Option<usize>,55 ) -> Result<Vec<u8>>;48 fn serialize(&self, results: &[BenchmarkResult], primary: MetricSelection) -> Result<Vec<u8>>;49}5051pub enum ExportTarget {52 File(String),
7 unmodified lines
6061/// Handles the management of multiple file exporters.62pub struct ExportManager {63 exporters: Vec<ExporterWithTarget>,71 time_unit: Option<TimeUnit>,72 sort_order: SortOrder,64 primary: MetricSelection,65}6667impl ExportManager {68 /// Build the ExportManager that will export the results specified69 /// in the given ArgMatches78 pub fn from_cli_arguments(79 matches: &ArgMatches,80 time_unit: Option<TimeUnit>,81 sort_order: SortOrder,82 ) -> Result<Self> {70 pub fn from_cli_arguments(matches: &ArgMatches, primary: MetricSelection) -> Result<Self> {71 let mut export_manager = Self {72 exporters: vec![],85 time_unit,86 sort_order,73 primary,74 };75 {76 let mut add_exporter = |flag, exporttype| -> Result<()> {77 if let Some(filename) = matches.get_one::<String>(flag) {
39 unmodified lines
117 /// is the final call after all benchmarks have been finished. In the former case,118 /// results are written to all file targets (to always have them up to date, even119 /// if a benchmark fails). In the latter case, we only print to stdout targets (in120 /// order not to clutter the output of hyperfine with intermediate results).134 /// `reference_index` refers to the complete benchmark sequence, so it can135 /// point past `results` while that benchmark is still pending.136 pub fn write_results(137 &self,138 results: &[BenchmarkResult],139 intermediate: bool,140 reference_index: Option<usize>,141 ) -> Result<()> {121 pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> {122 for e in &self.exporters {143 let content = || {144 e.exporter145 .serialize(results, self.time_unit, self.sort_order, reference_index)146 };123 let content = || e.exporter.serialize(results, self.primary);124125 match e.target {126 ExportTarget::File(ref filename) => {127 if intermediate {
26 unmodified lines
modified:src/export/tests.rs+138 added-125 removed
1use super::Exporter;2use crate::benchmark::benchmark_result::BenchmarkResult;3use crate::benchmark::measurement::{Measurement, Measurements};4use crate::export::asciidoc::AsciidocExporter;5use crate::export::markdown::MarkdownExporter;6use crate::export::orgmode::OrgmodeExporter;6use crate::quantity::{byte, second, Information, Time, TimeUnit, Zero};7use crate::{export::markdown::MarkdownExporter, options::SortOrder};7use crate::metric::{MetricSelection, Unit};8use crate::quantity::{byte, second, Information, Time, Zero};9use std::collections::BTreeMap;10use std::process::ExitStatus;1111fn get_output<E: Exporter + Default>(12 results: &[BenchmarkResult],13 unit: Option<TimeUnit>,14 sort_order: SortOrder,15) -> String {12fn get_output<E: Exporter + Default>(results: &[BenchmarkResult], unit: Option<Unit>) -> String {13 let exporter = E::default();17 String::from_utf8(exporter.serialize(results, unit, sort_order, None).unwrap()).unwrap()14 String::from_utf8(15 exporter16 .serialize(17 results,18 MetricSelection {19 unit,20 ..MetricSelection::default()21 },22 )23 .unwrap(),24 )25 .unwrap()26}2728/// Ensure the makrup output includes the table header and the multiple29/// benchmark results as a table. The list of actual times is not included
10 unmodified lines
40 display_name: String::from("sleep 0.1"),41 measurements: Measurements::new(vec![42 Measurement {43 time_wall_clock: Time::new::<second>(0.09),44 time_cpu: Time::new::<second>(0.09),45 time_user: Time::new::<second>(0.09),46 time_system: Time::zero(),47 memory_peak_resident: Some(Information::new::<byte>(1024.)),48 hardware_counters: Default::default(),49 exit_status: ExitStatus::default(),50 },51 Measurement {52 time_wall_clock: Time::new::<second>(0.10),53 time_cpu: Time::new::<second>(0.10),54 time_user: Time::new::<second>(0.10),55 time_system: Time::zero(),56 memory_peak_resident: Some(Information::new::<byte>(1024.)),57 hardware_counters: Default::default(),58 exit_status: ExitStatus::default(),59 },60 Measurement {61 time_wall_clock: Time::new::<second>(0.14),62 time_cpu: Time::new::<second>(0.14),63 time_user: Time::new::<second>(0.14),64 time_system: Time::zero(),65 memory_peak_resident: Some(Information::new::<byte>(1024.)),66 hardware_counters: Default::default(),
8 unmodified lines
75 display_name: String::from("sleep 2"),76 measurements: Measurements::new(vec![77 Measurement {78 time_wall_clock: Time::new::<second>(2.0),79 time_cpu: Time::new::<second>(2.0),80 time_user: Time::new::<second>(2.0),81 time_system: Time::zero(),82 memory_peak_resident: Some(Information::new::<byte>(1024.)),83 hardware_counters: Default::default(),84 exit_status: ExitStatus::default(),85 },86 Measurement {87 time_wall_clock: Time::new::<second>(3.0),88 time_cpu: Time::new::<second>(3.0),89 time_user: Time::new::<second>(3.0),90 time_system: Time::zero(),91 memory_peak_resident: Some(Information::new::<byte>(1024.)),92 hardware_counters: Default::default(),93 exit_status: ExitStatus::default(),94 },95 Measurement {96 time_wall_clock: Time::new::<second>(4.0),97 time_cpu: Time::new::<second>(4.0),98 time_user: Time::new::<second>(4.0),99 time_system: Time::zero(),100 memory_peak_resident: Some(Information::new::<byte>(1024.)),101 hardware_counters: Default::default(),
3 unmodified lines
105 parameters: BTreeMap::new(),106 },107 ];10895 insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, None, SortOrder::Command), @r#"96 | Command | Mean [ms] | Min [ms] | Max [ms] | Relative |97 |:---|---:|---:|---:|---:|98 | `sleep 0.1` | 110.0 ± 26.5 | 90.0 | 140.0 | 1.00 |99 | `sleep 2` | 3000.0 ± 1000.0 | 2000.0 | 4000.0 | 27.27 ± 11.21 |100 "#);109 insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, None), @"110 | Command | Mean Wall Time [ms] | Change | Factor |111 |:---|---:|---:|:---|112 | `sleep 0.1` | 110.0 ± 26.5 | | |113 | `sleep 2` | 3000.0 ± 1000.0 | +2627.3% | (27.3x slower) |114 ");115102 insta::assert_snapshot!(get_output::<AsciidocExporter>(&results, None, SortOrder::Command), @r#"103 [cols="<,>,>,>,>"]116 insta::assert_snapshot!(get_output::<AsciidocExporter>(&results, None), @r#"117 [cols="<,>,>,<"]118 |===105 | Command 106 | Mean [ms] 107 | Min [ms] 108 | Max [ms] 109 | Relative 119 | Command120 | Mean Wall Time [ms]121 | Change122 | Factor123111 | `sleep 0.1` 112 | 110.0 ± 26.5 113 | 90.0 114 | 140.0 115 | 1.00 124 | `sleep 0.1`125 | 110.0 ± 26.5126 |127 |128117 | `sleep 2` 118 | 3000.0 ± 1000.0 119 | 2000.0 120 | 4000.0 121 | 27.27 ± 11.21 129 | `sleep 2`130 | 3000.0 ± 1000.0131 | +2627.3%132 | (27.3x slower)133 |===134 "#);135125 insta::assert_snapshot!(get_output::<OrgmodeExporter>(&results, None, SortOrder::Command), @r#"126 | Command | Mean [ms] | Min [ms] | Max [ms] | Relative |127 |--+--+--+--+--|128 | =sleep 0.1= | 110.0 ± 26.5 | 90.0 | 140.0 | 1.00 |129 | =sleep 2= | 3000.0 ± 1000.0 | 2000.0 | 4000.0 | 27.27 ± 11.21 |130 "#);136 insta::assert_snapshot!(get_output::<OrgmodeExporter>(&results, None), @"137 | Command | Mean Wall Time [ms] | Change | Factor |138 |--+--+--+--|139 | =sleep 0.1= | 110.0 ± 26.5 | | |140 | =sleep 2= | 3000.0 ± 1000.0 | +2627.3% | (27.3x slower) |141 ");142}143144/// This (again) demonstrates that the first entry's units (s) are used to set145/// the units for all entries when the time unit is not given.
6 unmodified lines
152 display_name: String::from("sleep 2"),153 measurements: Measurements::new(vec![154 Measurement {155 time_wall_clock: Time::new::<second>(2.1),156 time_cpu: Time::new::<second>(2.1),157 time_user: Time::new::<second>(2.1),158 time_system: Time::zero(),159 memory_peak_resident: Some(Information::new::<byte>(1024.)),160 hardware_counters: Default::default(),161 exit_status: ExitStatus::default(),162 },163 Measurement {164 time_wall_clock: Time::new::<second>(2.2),165 time_cpu: Time::new::<second>(2.2),166 time_user: Time::new::<second>(2.2),167 time_system: Time::zero(),168 memory_peak_resident: Some(Information::new::<byte>(1024.)),169 hardware_counters: Default::default(),170 exit_status: ExitStatus::default(),171 },172 Measurement {173 time_wall_clock: Time::new::<second>(2.3),174 time_cpu: Time::new::<second>(2.3),175 time_user: Time::new::<second>(2.3),176 time_system: Time::zero(),177 memory_peak_resident: Some(Information::new::<byte>(1024.)),178 hardware_counters: Default::default(),
8 unmodified lines
187 display_name: String::from("sleep 0.1"),188 measurements: Measurements::new(vec![189 Measurement {190 time_wall_clock: Time::new::<second>(0.1),191 time_cpu: Time::new::<second>(0.1),192 time_user: Time::new::<second>(0.1),193 time_system: Time::zero(),194 memory_peak_resident: Some(Information::new::<byte>(1024.)),195 hardware_counters: Default::default(),196 exit_status: ExitStatus::default(),197 },198 Measurement {199 time_wall_clock: Time::new::<second>(0.2),200 time_cpu: Time::new::<second>(0.2),201 time_user: Time::new::<second>(0.2),202 time_system: Time::zero(),203 memory_peak_resident: Some(Information::new::<byte>(1024.)),204 hardware_counters: Default::default(),205 exit_status: ExitStatus::default(),206 },207 Measurement {208 time_wall_clock: Time::new::<second>(0.3),209 time_cpu: Time::new::<second>(0.3),210 time_user: Time::new::<second>(0.3),211 time_system: Time::zero(),212 memory_peak_resident: Some(Information::new::<byte>(1024.)),213 hardware_counters: Default::default(),
3 unmodified lines
217 parameters: BTreeMap::new(),218 },219 ];220204 insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, None, SortOrder::Command), @r#"205 | Command | Mean [s] | Min [s] | Max [s] | Relative |206 |:---|---:|---:|---:|---:|207 | `sleep 2` | 2.200 ± 0.100 | 2.100 | 2.300 | 11.00 ± 5.52 |208 | `sleep 0.1` | 0.200 ± 0.100 | 0.100 | 0.300 | 1.00 |209 "#);221 insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, None), @"222 | Command | Mean Wall Time [s] | Change | Factor |223 |:---|---:|---:|:---|224 | `sleep 2` | 2.200 ± 0.100 | | |225 | `sleep 0.1` | 0.200 ± 0.100 | -90.9% | (11.0x faster) |226 ");227211 insta::assert_snapshot!(get_output::<AsciidocExporter>(&results, None, SortOrder::Command), @r#"212 [cols="<,>,>,>,>"]228 insta::assert_snapshot!(get_output::<AsciidocExporter>(&results, None), @r#"229 [cols="<,>,>,<"]230 |===214 | Command 215 | Mean [s] 216 | Min [s] 217 | Max [s] 218 | Relative 231 | Command232 | Mean Wall Time [s]233 | Change234 | Factor235220 | `sleep 2` 221 | 2.200 ± 0.100 222 | 2.100 223 | 2.300 224 | 11.00 ± 5.52 236 | `sleep 2`237 | 2.200 ± 0.100238 |239 |240226 | `sleep 0.1` 227 | 0.200 ± 0.100 228 | 0.100 229 | 0.300 230 | 1.00 241 | `sleep 0.1`242 | 0.200 ± 0.100243 | -90.9%244 | (11.0x faster)245 |===246 "#);247234 insta::assert_snapshot!(get_output::<OrgmodeExporter>(&results, None, SortOrder::Command), @r#"235 | Command | Mean [s] | Min [s] | Max [s] | Relative |236 |--+--+--+--+--|237 | =sleep 2= | 2.200 ± 0.100 | 2.100 | 2.300 | 11.00 ± 5.52 |238 | =sleep 0.1= | 0.200 ± 0.100 | 0.100 | 0.300 | 1.00 |239 "#);248 insta::assert_snapshot!(get_output::<OrgmodeExporter>(&results, None), @"249 | Command | Mean Wall Time [s] | Change | Factor |250 |--+--+--+--|251 | =sleep 2= | 2.200 ± 0.100 | | |252 | =sleep 0.1= | 0.200 ± 0.100 | -90.9% | (11.0x faster) |253 ");254}255256/// This (again) demonstrates that the given time unit (ms) is used to set257/// the units for all entries.
6 unmodified lines
264 display_name: String::from("sleep 2"),265 measurements: Measurements::new(vec![266 Measurement {267 time_wall_clock: Time::new::<second>(2.1),268 time_cpu: Time::new::<second>(2.1),269 time_user: Time::new::<second>(2.1),270 time_system: Time::zero(),271 memory_peak_resident: Some(Information::new::<byte>(1024.)),272 hardware_counters: Default::default(),273 exit_status: ExitStatus::default(),274 },275 Measurement {276 time_wall_clock: Time::new::<second>(2.2),277 time_cpu: Time::new::<second>(2.2),278 time_user: Time::new::<second>(2.2),279 time_system: Time::zero(),280 memory_peak_resident: Some(Information::new::<byte>(1024.)),281 hardware_counters: Default::default(),282 exit_status: ExitStatus::default(),283 },284 Measurement {285 time_wall_clock: Time::new::<second>(2.3),286 time_cpu: Time::new::<second>(2.3),287 time_user: Time::new::<second>(2.3),288 time_system: Time::zero(),289 memory_peak_resident: Some(Information::new::<byte>(1024.)),290 hardware_counters: Default::default(),
8 unmodified lines
299 display_name: String::from("sleep 0.1"),300 measurements: Measurements::new(vec![301 Measurement {302 time_wall_clock: Time::new::<second>(0.1),303 time_cpu: Time::new::<second>(0.1),304 time_user: Time::new::<second>(0.1),305 time_system: Time::zero(),306 memory_peak_resident: Some(Information::new::<byte>(1024.)),307 hardware_counters: Default::default(),308 exit_status: ExitStatus::default(),309 },310 Measurement {311 time_wall_clock: Time::new::<second>(0.2),312 time_cpu: Time::new::<second>(0.2),313 time_user: Time::new::<second>(0.2),314 time_system: Time::zero(),315 memory_peak_resident: Some(Information::new::<byte>(1024.)),316 hardware_counters: Default::default(),317 exit_status: ExitStatus::default(),318 },319 Measurement {320 time_wall_clock: Time::new::<second>(0.3),321 time_cpu: Time::new::<second>(0.3),322 time_user: Time::new::<second>(0.3),323 time_system: Time::zero(),324 memory_peak_resident: Some(Information::new::<byte>(1024.)),325 hardware_counters: Default::default(),
3 unmodified lines
329 parameters: BTreeMap::new(),330 },331 ];332313 insta::assert_snapshot!(get_output::<MarkdownExporter>(&timing_results, Some(TimeUnit::MilliSecond), SortOrder::Command), @r#"314 | Command | Mean [ms] | Min [ms] | Max [ms] | Relative |315 |:---|---:|---:|---:|---:|316 | `sleep 2` | 2200.0 ± 100.0 | 2100.0 | 2300.0 | 11.00 ± 5.52 |317 | `sleep 0.1` | 200.0 ± 100.0 | 100.0 | 300.0 | 1.00 |318 "#);333 insta::assert_snapshot!(get_output::<MarkdownExporter>(&timing_results, Some(Unit { symbol: "ms", scale: 0.001 })), @"334 | Command | Mean Wall Time [ms] | Change | Factor |335 |:---|---:|---:|:---|336 | `sleep 2` | 2200.0 ± 100.0 | | |337 | `sleep 0.1` | 200.0 ± 100.0 | -90.9% | (11.0x faster) |338 ");339320 insta::assert_snapshot!(get_output::<AsciidocExporter>(&timing_results, Some(TimeUnit::MilliSecond), SortOrder::Command), @r#"321 [cols="<,>,>,>,>"]340 insta::assert_snapshot!(get_output::<AsciidocExporter>(&timing_results, Some(Unit { symbol: "ms", scale: 0.001 })), @r#"341 [cols="<,>,>,<"]342 |===323 | Command 324 | Mean [ms] 325 | Min [ms] 326 | Max [ms] 327 | Relative 343 | Command344 | Mean Wall Time [ms]345 | Change346 | Factor347329 | `sleep 2` 330 | 2200.0 ± 100.0 331 | 2100.0 332 | 2300.0 333 | 11.00 ± 5.52 348 | `sleep 2`349 | 2200.0 ± 100.0350 |351 |352335 | `sleep 0.1` 336 | 200.0 ± 100.0 337 | 100.0 338 | 300.0 339 | 1.00 353 | `sleep 0.1`354 | 200.0 ± 100.0355 | -90.9%356 | (11.0x faster)357 |===358 "#);359343 insta::assert_snapshot!(get_output::<OrgmodeExporter>(&timing_results, Some(TimeUnit::MilliSecond), SortOrder::Command), @r#"344 | Command | Mean [ms] | Min [ms] | Max [ms] | Relative |345 |--+--+--+--+--|346 | =sleep 2= | 2200.0 ± 100.0 | 2100.0 | 2300.0 | 11.00 ± 5.52 |347 | =sleep 0.1= | 200.0 ± 100.0 | 100.0 | 300.0 | 1.00 |348 "#);360 insta::assert_snapshot!(get_output::<OrgmodeExporter>(&timing_results, Some(Unit { symbol: "ms", scale: 0.001 })), @"361 | Command | Mean Wall Time [ms] | Change | Factor |362 |--+--+--+--|363 | =sleep 2= | 2200.0 ± 100.0 | | |364 | =sleep 0.1= | 200.0 ± 100.0 | -90.9% | (11.0x faster) |365 ");366}367368/// The given time unit (s) is used to set the units for all entries.369#[test]
5 unmodified lines
375 display_name: String::from("sleep 2"),376 measurements: Measurements::new(vec![377 Measurement {378 time_wall_clock: Time::new::<second>(2.01),379 time_cpu: Time::new::<second>(2.01),380 time_user: Time::new::<second>(2.01),381 time_system: Time::zero(),382 memory_peak_resident: Some(Information::new::<byte>(1024.)),383 hardware_counters: Default::default(),384 exit_status: ExitStatus::default(),385 },386 Measurement {387 time_wall_clock: Time::new::<second>(2.02),388 time_cpu: Time::new::<second>(2.02),389 time_user: Time::new::<second>(2.02),390 time_system: Time::zero(),391 memory_peak_resident: Some(Information::new::<byte>(1024.)),392 hardware_counters: Default::default(),393 exit_status: ExitStatus::default(),394 },395 Measurement {396 time_wall_clock: Time::new::<second>(2.03),397 time_cpu: Time::new::<second>(2.03),398 time_user: Time::new::<second>(2.03),399 time_system: Time::zero(),400 memory_peak_resident: Some(Information::new::<byte>(1024.)),401 hardware_counters: Default::default(),
8 unmodified lines
410 display_name: String::from("sleep 0.1"),411 measurements: Measurements::new(vec![412 Measurement {413 time_wall_clock: Time::new::<second>(0.11),414 time_cpu: Time::new::<second>(0.11),415 time_user: Time::new::<second>(0.11),416 time_system: Time::zero(),417 memory_peak_resident: Some(Information::new::<byte>(1024.)),418 hardware_counters: Default::default(),419 exit_status: ExitStatus::default(),420 },421 Measurement {422 time_wall_clock: Time::new::<second>(0.12),423 time_cpu: Time::new::<second>(0.12),424 time_user: Time::new::<second>(0.12),425 time_system: Time::zero(),426 memory_peak_resident: Some(Information::new::<byte>(1024.)),427 hardware_counters: Default::default(),428 exit_status: ExitStatus::default(),429 },430 Measurement {431 time_wall_clock: Time::new::<second>(0.13),432 time_cpu: Time::new::<second>(0.13),433 time_user: Time::new::<second>(0.13),434 time_system: Time::zero(),435 memory_peak_resident: Some(Information::new::<byte>(1024.)),436 hardware_counters: Default::default(),
3 unmodified lines
440 parameters: BTreeMap::new(),441 },442 ];443421 insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, Some(TimeUnit::Second), SortOrder::Command), @r#"422 | Command | Mean [s] | Min [s] | Max [s] | Relative |423 |:---|---:|---:|---:|---:|424 | `sleep 2` | 2.020 ± 0.010 | 2.010 | 2.030 | 16.83 ± 1.41 |425 | `sleep 0.1` | 0.120 ± 0.010 | 0.110 | 0.130 | 1.00 |426 "#);444 insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, Some(Unit { symbol: "s", scale: 1.0 })), @"445 | Command | Mean Wall Time [s] | Change | Factor |446 |:---|---:|---:|:---|447 | `sleep 2` | 2.020 ± 0.010 | | |448 | `sleep 0.1` | 0.120 ± 0.010 | -94.1% | (16.8x faster) |449 ");450428 insta::assert_snapshot!(get_output::<MarkdownExporter>(&results, Some(TimeUnit::Second), SortOrder::MeanTime), @r#"429 | Command | Mean [s] | Min [s] | Max [s] | Relative |430 |:---|---:|---:|---:|---:|431 | `sleep 0.1` | 0.120 ± 0.010 | 0.110 | 0.130 | 1.00 |432 | `sleep 2` | 2.020 ± 0.010 | 2.010 | 2.030 | 16.83 ± 1.41 |433 "#);434435 insta::assert_snapshot!(get_output::<AsciidocExporter>(&results, Some(TimeUnit::Second), SortOrder::Command), @r#"436 [cols="<,>,>,>,>"]451 insta::assert_snapshot!(get_output::<AsciidocExporter>(&results, Some(Unit { symbol: "s", scale: 1.0 })), @r#"452 [cols="<,>,>,<"]453 |===438 | Command 439 | Mean [s] 440 | Min [s] 441 | Max [s] 442 | Relative 454 | Command455 | Mean Wall Time [s]456 | Change457 | Factor458444 | `sleep 2` 445 | 2.020 ± 0.010 446 | 2.010 447 | 2.030 448 | 16.83 ± 1.41 459 | `sleep 2`460 | 2.020 ± 0.010461 |462 |463450 | `sleep 0.1` 451 | 0.120 ± 0.010 452 | 0.110 453 | 0.130 454 | 1.00 464 | `sleep 0.1`465 | 0.120 ± 0.010466 | -94.1%467 | (16.8x faster)468 |===469 "#);470}
modified:src/output/mod.rs+1 added
1pub mod progress_bar;2pub mod report;3pub mod warnings;45/// Mark console write errors so broken pipes can be handled separately from file errors.6macro_rules! console_writeln {
7 unmodified lines
modified:src/output/progress_bar.rs+22 added-15 removed
14 unmodified lines
15const DEFAULT_TEMPLATE: &str = " {spinner} {msg:<30} {wide_bar} ETA {eta_precise} ";16const INITIAL_TEMPLATE: &str =17 " {spinner} Initial run: {initial_elapsed:<17} {wide_bar} ETA {eta_precise} ";1819fn style_with_template(bar: &ProgressBar, template: &str) -> ProgressStyle {20 let template = if bar.prefix().is_empty() {21 template.to_owned()22 } else {23 format!("{{prefix}}\n{template}")24 };25 bar.style().template(&template).expect("no template error")26}2728/// Show the benchmark heading above the progress bar, clearing both on completion.29pub fn set_benchmark_header(bar: &ProgressBar, header: String) {30 bar.set_prefix(header);31 bar.set_style(style_with_template(bar, DEFAULT_TEMPLATE));32}3334/// Show the time elapsed since the initial benchmark command started.35pub fn start_initial_measurement(bar: &ProgressBar, started: Instant) {21 let style = bar22 .style()23 .template(INITIAL_TEMPLATE)24 .expect("no template error")25 .with_key(26 "initial_elapsed",27 move |_: &ProgressState, w: &mut dyn fmt::Write| {28 write!(w, "{}", FormattedDuration(started.elapsed())).unwrap();29 },30 );36 let style = style_with_template(bar, INITIAL_TEMPLATE).with_key(37 "initial_elapsed",38 move |_: &ProgressState, w: &mut dyn fmt::Write| {39 write!(w, "{}", FormattedDuration(started.elapsed())).unwrap();40 },41 );42 bar.set_style(style);43}4445/// Stop showing the initial timer and display the next phase's message.46pub fn finish_initial_measurement(bar: &ProgressBar, message: String) {47 bar.set_message(message);37 bar.set_style(38 bar.style()39 .template(DEFAULT_TEMPLATE)40 .expect("no template error"),41 );48 bar.set_style(style_with_template(bar, DEFAULT_TEMPLATE));49}5051/// Return a pre-configured progress bar52pub fn get_progress_bar(length: u64, msg: &str, option: OutputStyleOption) -> ProgressBar {
18 unmodified lines
added:src/output/report.rs+197 added
1use std::io::{self, Write};23use anyhow::{ensure, Result};4use colored::Colorize;56use crate::benchmark::{benchmark_result::BenchmarkResult, measurement::Measurements};7use crate::metric::MetricSelection;8use crate::output::console_writeln;910// Reserve enough space for typical values and every supported unit suffix so11// independently printed benchmarks keep the same layout.12const MIN_VALUE_WIDTH: usize = 7;13const MIN_UNIT_WIDTH: usize = 3;14const MIN_CHANGE_WIDTH: usize = 14;1516/// Print a completed benchmark immediately, comparing every metric with benchmark 1.17pub fn print(18 number: usize,19 name: &str,20 measurements: &Measurements,21 metrics: &[MetricSelection],22 skip_unavailable_metrics: bool,23 reference: Option<&BenchmarkResult>,24) -> Result<()> {25 let comparison = reference.is_some();26 let multiple_runs = measurements.len() > 1;27 let value_columns = 1..if multiple_runs { 5 } else { 2 };28 let mut header = vec![29 String::new(),30 "mean".to_owned(),31 "σ".to_owned(),32 "min".to_owned(),33 "max".to_owned(),34 ];35 if !multiple_runs {36 header.truncate(2);37 header[1] = "Value".to_owned();38 }39 if comparison {40 header.extend([String::new(), String::new()]);41 }42 let mut rows = vec![(header, "")];43 for selection in metrics {44 let Some(summary) = selection.metric.summarize(measurements) else {45 ensure!(46 skip_unavailable_metrics,47 "Metric '{}' is unavailable for '{name}'",48 selection.metric.name()49 );50 continue;51 };52 let baseline = reference.and_then(|r| selection.metric.summarize(&r.measurements));53 // Keep auto units consistent with the first command for easier comparison.54 let scale_mean = baseline55 .as_ref()56 .filter(|stats| stats.mean != 0.0)57 .unwrap_or(&summary)58 .mean;59 let unit = selection.display_unit(scale_mean);60 let mut row = vec![61 selection.metric.label().to_owned(),62 unit.format_value(summary.mean),63 ];64 if let Some(stddev) = summary.stddev {65 row.push(unit.format_value(stddev));66 row.push(unit.format_value(summary.min));67 row.push(unit.format_value(summary.max));68 }69 if comparison {70 row.push(baseline.as_ref().map_or_else(71 || "N/A".to_owned(),72 |baseline| summary.format_change_from(baseline),73 ));74 row.push(baseline.as_ref().map_or_else(String::new, |baseline| {75 summary.format_factor_from(baseline, selection.metric)76 }));77 }78 rows.push((79 row,80 if unit.symbol == "count" {81 ""82 } else {83 unit.symbol84 },85 ));86 }87 // Align numbers and unit suffixes independently so mixed units do not shift88 // the values or the ± and … separators.89 let unit_width = rows90 .iter()91 .map(|(_, unit)| unit.chars().count())92 .max()93 .unwrap()94 .max(MIN_UNIT_WIDTH);95 // Keep labels aligned across benchmarks even when some metrics are skipped.96 let metric_width = metrics97 .iter()98 .map(|selection| selection.metric.label().chars().count())99 .max()100 .unwrap_or(0);101 let widths: Vec<_> = (0..rows[0].0.len())102 .map(|column| {103 let width = rows104 .iter()105 .map(|(row, _)| row[column].chars().count())106 .max()107 .unwrap();108 if column == 0 {109 width.max(metric_width)110 } else if value_columns.contains(&column) {111 width.max(MIN_VALUE_WIDTH)112 } else {113 width.max(MIN_CHANGE_WIDTH)114 }115 })116 .collect();117 let mut stdout = io::stdout().lock();118 console_writeln!(119 stdout,120 "{}: {} {}",121 format!("Benchmark {}", number + 1).bold(),122 name.white().bold(),123 format!(124 "({} {})",125 measurements.len(),126 if measurements.len() == 1 {127 "run"128 } else {129 "runs"130 }131 )132 .dimmed()133 )?;134 for (index, (row, unit)) in rows.iter().enumerate() {135 let mut line = String::new();136 for (column, value) in row.iter().enumerate() {137 let is_factor = comparison && column == row.len() - 1;138 let is_change = comparison && column >= row.len() - 2;139 if index == 0 && is_change {140 break;141 }142 if column > 0 {143 line.push_str(match (multiple_runs, column) {144 (true, 2) => " ± ",145 (true, 4) => " … ",146 _ => " ",147 });148 }149 let padding = " ".repeat(widths[column] - value.chars().count());150 let has_unit = value_columns.contains(&column);151 let text = if has_unit && !unit.is_empty() {152 format!("{value} {unit}")153 } else {154 value.clone()155 };156 let styled = if is_change {157 if row[row.len() - 2].starts_with('-') {158 text.green().to_string()159 } else if row[row.len() - 2].starts_with('+') {160 text.red().to_string()161 } else {162 text.normal().to_string()163 }164 } else if column == 1 || column == 2 {165 text.green().to_string()166 } else if column == 3 {167 text.cyan().to_string()168 } else if column == 4 {169 text.purple().to_string()170 } else {171 text.normal().to_string()172 };173 if column == 0 || is_factor {174 line.push_str(&format!("{styled}{padding}"));175 } else {176 line.push_str(&format!("{padding}{styled}"));177 }178 if has_unit && unit_width > 0 {179 // Empty suffixes (headers and unscaled counters) also need the180 // space normally separating a number from its unit.181 let unit_padding = unit_width - unit.chars().count() + usize::from(unit.is_empty());182 line.push_str(&" ".repeat(unit_padding));183 }184 }185 let line = line.trim_end();186 console_writeln!(187 stdout,188 " {}",189 if index == 1 {190 line.bold()191 } else {192 line.normal()193 }194 )?;195 }196 Ok(())197}
modified:src/output/warnings.rs+14 added-17 removed
1use std::fmt;23use crate::benchmark::MIN_EXECUTION_TIME;4use crate::quantity::{FormatQuantity, Time, TimeUnit};4use crate::metric::{Metric, MetricSelection};5use crate::quantity::millisecond;67pub struct OutlierWarningOptions {8 pub warmup_in_use: bool,9 pub prepare_in_use: bool,
2 unmodified lines
12/// A list of all possible warnings13pub enum Warnings {14 FastExecutionTime,15 NonZeroExitCode,15 SlowInitialRun(Time, OutlierWarningOptions),16 OutliersDetected(OutlierWarningOptions),16 InitialRunOutlier(MetricSelection, f64, OutlierWarningOptions),17}1819impl fmt::Display for Warnings {20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {21 match *self {22 Warnings::FastExecutionTime => write!(23 f,24 "Command took less than {} ms to complete. Note that the results might be \24 "Command took less than {} ms to complete. Note that the wall-clock measurements might be \25 inaccurate because hyperfine can not calibrate the shell startup time much \26 more precise than this limit. You can try to use the `-N`/`--shell=none` \27 option to disable the shell completely.",28 MIN_EXECUTION_TIME.format_with_precision(TimeUnit::MilliSecond, 0)28 MIN_EXECUTION_TIME.get::<millisecond>()29 ),30 Warnings::NonZeroExitCode => write!(f, "Ignoring non-zero exit code."),31 Warnings::SlowInitialRun(time_first_run, ref options) => write!(31 Warnings::InitialRunOutlier(selection, value, _) if selection.metric != Metric::TimeWallClock => write!(32 f,33 "The first benchmarking run for this command had an unusually high value for the primary '{}' metric ({}) compared with the rest.",34 selection.metric.name(),35 selection.display_unit(value).format(value),36 ),37 Warnings::InitialRunOutlier(selection, value, ref options) => write!(38 f,39 "The first benchmarking run for this command was significantly slower than the \40 rest ({time}). This could be caused by (filesystem) caches that were not filled until \41 after the first run. {hints}",36 time=time_first_run.format_auto(),42 time=selection.display_unit(value).format(value),43 hints=match (options.warmup_in_use, options.prepare_in_use) {44 (true, true) => "You are already using both the '--warmup' option as well \45 as the '--prepare' option. Consider re-running the benchmark on a quiet system. \46 Maybe it was a random outlier. Alternatively, consider increasing the warmup \
11 unmodified lines
58 those caches before the actual benchmark. Alternatively, use the '--prepare' \59 option to clear the caches before each timing run."60 }61 ),56 Warnings::OutliersDetected(ref options) => write!(57 f,58 "Statistical outliers were detected. Consider re-running this benchmark on a quiet \59 system without any interferences from other programs.{hint}",60 hint=if options.warmup_in_use && options.prepare_in_use {61 ""62 } else {63 " It might help to use the '--warmup' or '--prepare' options."64 }65 ),6263 }64 }65}
modified:src/quantity/mod.rs-181 removed
9 unmodified lines
10pub use si::ratio::ratio;11pub use si::time::{hour, microsecond, millisecond, minute, nanosecond, second};12pub use uom::num_traits::Zero;1314pub use units::{InformationUnit, IsUnit, TimeUnit};1514pub mod statistics;17mod units;1519pub trait QuantityInUnit<U> {20 fn value_in_unit(self) -> f64;21}2223impl<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}2829impl<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}3637impl<U: uom::si::ratio::Unit + uom::Conversion<f64, T = f64>> QuantityInUnit<U> for Ratio {38 fn value_in_unit(self) -> f64 {39 self.get::<U>()40 }41}4243pub trait FormatQuantity {44 type Unit;4546 fn suitable_unit(&self) -> Self::Unit;4748 fn format_with_precision(&self, unit: Self::Unit, precision: usize) -> String;49 fn format(&self, unit: Self::Unit) -> String;50 fn format_auto(&self) -> String;51 fn format_value(&self, unit: Self::Unit) -> String;52}5354impl FormatQuantity for Time {55 type Unit = TimeUnit;5657 fn suitable_unit(&self) -> TimeUnit {58 if *self < Time::new::<millisecond>(1.0) {59 TimeUnit::MicroSecond60 } else if *self < Time::new::<second>(1.0) {61 TimeUnit::MilliSecond62 } else {63 TimeUnit::Second64 }65 }6667 /// Format the time duration in the given unit with the given precision.68 fn format_with_precision(&self, u: TimeUnit, precision: usize) -> String {69 u.format(*self, precision)70 }7172 /// Format the time duration in the given unit.73 fn format(&self, unit: TimeUnit) -> String {74 let value = self.format_with_precision(unit, unit.preferred_precision());75 format!("{} {}", value, unit.short_name())76 }7778 /// Format the given time duration. The unit will be determined automatically.79 fn format_auto(&self) -> String {80 self.format(self.suitable_unit())81 }8283 /// Like `format`, but without displaying the unit.84 fn format_value(&self, unit: TimeUnit) -> String {85 self.format_with_precision(unit, unit.preferred_precision())86 }87}8816pub const fn const_time_from_seconds(value: f64) -> Time {17 // Quantity::new in uom is not yet const: https://docs.rs/uom/0.36.0/uom/si/struct.Quantity.html18 Time {19 dimension: PhantomData,
1 unmodified line
21 value,22 }23}2498impl FormatQuantity for Information {99 type Unit = InformationUnit;100101 fn suitable_unit(&self) -> InformationUnit {102 if *self < Information::new::<kibibyte>(1.0) {103 InformationUnit::Byte104 } else if *self < Information::new::<mebibyte>(1.0) {105 InformationUnit::KibiByte106 } else if *self < Information::new::<gibibyte>(1.0) {107 InformationUnit::MebiByte108 } else {109 InformationUnit::GibiByte110 }111 }112113 /// Format the information in the given unit with the given precision.114 fn format_with_precision(&self, u: InformationUnit, precision: usize) -> String {115 u.format(*self, precision)116 }117118 /// Format the information in the given unit.119 fn format(&self, unit: InformationUnit) -> String {120 let value = self.format_with_precision(unit, unit.preferred_precision());121 format!("{} {}", value, unit.short_name())122 }123124 /// Format the given information. The unit will be determined automatically.125 fn format_auto(&self) -> String {126 self.format(self.suitable_unit())127 }128129 /// Like `format`, but without displaying the unit.130 fn format_value(&self, unit: InformationUnit) -> String {131 self.format_with_precision(unit, unit.preferred_precision())132 }133}13425pub fn serialize_time<S>(t: &Time, s: S) -> Result<S::Ok, S::Error>26where27 S: Serializer,28{
37 unmodified lines
6667 let largest_exactly_representable = Information::new::<byte>(9_007_199_254_740_992.);68 assert_eq!(largest_exactly_representable.get::<pebibyte>(), 8.);69}180181#[test]182fn test_suiteable_unit_time() {183 assert_eq!(Time::new::<second>(1.3).suitable_unit(), TimeUnit::Second);184 assert_eq!(Time::new::<second>(1.0).suitable_unit(), TimeUnit::Second);185 assert_eq!(186 Time::new::<second>(0.999).suitable_unit(),187 TimeUnit::MilliSecond188 );189 assert_eq!(190 Time::new::<second>(0.0005).suitable_unit(),191 TimeUnit::MicroSecond192 );193 assert_eq!(194 Time::new::<second>(0.).suitable_unit(),195 TimeUnit::MicroSecond196 );197 assert_eq!(198 Time::new::<second>(1000.0).suitable_unit(),199 TimeUnit::Second200 );201}202203#[test]204fn test_suitable_unit_information() {205 assert_eq!(206 Information::new::<byte>(512.0).suitable_unit(),207 InformationUnit::Byte208 );209 assert_eq!(210 Information::new::<byte>(2048.0).suitable_unit(),211 InformationUnit::KibiByte212 );213 assert_eq!(214 Information::new::<byte>(2_097_152.0).suitable_unit(),215 InformationUnit::MebiByte216 );217 assert_eq!(218 Information::new::<byte>(2_147_483_648.0).suitable_unit(),219 InformationUnit::GibiByte220 );221}222223#[test]224fn test_format() {225 let time = Time::new::<millisecond>(123.4);226 assert_eq!(time.format(TimeUnit::Second), "0.123 s");227 assert_eq!(time.format(TimeUnit::MilliSecond), "123.4 ms");228 assert_eq!(time.format_auto(), "123.4 ms");229 assert_eq!(time.format(TimeUnit::MicroSecond), "123400.0 µs");230231 let memory_peak_resident = Information::new::<kibibyte>(8.);232 assert_eq!(memory_peak_resident.format_auto(), "8.0 KiB");233 assert_eq!(memory_peak_resident.format(InformationUnit::Byte), "8192 B");234 assert_eq!(235 memory_peak_resident.format(InformationUnit::KibiByte),236 "8.0 KiB"237 );238}239240#[test]241fn test_format_duration_unit_with_unit() {242 let out = Time::new::<second>(1.3).format(TimeUnit::Second);243 assert_eq!("1.300 s", out);244245 let out = Time::new::<second>(1.3).format(TimeUnit::MilliSecond);246 assert_eq!("1300.0 ms", out);247248 let out = Time::new::<second>(1.3).format(TimeUnit::MicroSecond);249 assert_eq!("1300000.0 µs", out);250}
modified:src/quantity/statistics.rs-5 removed
144 unmodified lines
145 // Compute modified Z-scores (x_i - x_median) / MAD146 xs.iter().map(|&x| (x - x_median) / mad).collect()147}148149pub fn modified_zscores<Q: UnsafeRawValue>(values: &[Q]) -> Vec<f64> {150 let values: Vec<_> = values.iter().map(|q| q.unsafe_raw_value()).collect();151 modified_zscores_f64(&values)152}153149#[cfg(test)]150mod tests {151 use super::*;152 use approx::assert_relative_eq;
83 unmodified lines
deleted:src/quantity/units.rs-166 removed
1//! This module contains common units for time and information quantities.23use std::marker::PhantomData;45use crate::quantity::{6 byte, gibibyte, hour, kibibyte, mebibyte, microsecond, millisecond, minute, second, tebibyte,7 Information, Time,8};910pub trait IsUnit {11 type Quantity;1213 fn dispatch(&self) -> Box<dyn UnitImpl<Quantity = Self::Quantity>>;1415 fn preferred_precision(&self) -> usize;1617 fn short_name(&self) -> &'static str {18 self.dispatch().short_name()19 }2021 fn format(&self, value: Self::Quantity, precision: usize) -> String {22 self.dispatch().format_value(value, precision)23 }24}2526/// Supported time units27#[derive(Debug, Clone, Copy, PartialEq, Eq)]28pub enum TimeUnit {29 MicroSecond,30 MilliSecond,31 Second,32 Minute,33 Hour,34}3536impl IsUnit for TimeUnit {37 type Quantity = Time;3839 fn dispatch(&self) -> Box<dyn UnitImpl<Quantity = Time>> {40 match self {41 TimeUnit::MicroSecond => Box::new(TimeUnitDispatcher::<microsecond>::new()),42 TimeUnit::MilliSecond => Box::new(TimeUnitDispatcher::<millisecond>::new()),43 TimeUnit::Second => Box::new(TimeUnitDispatcher::<second>::new()),44 TimeUnit::Minute => Box::new(TimeUnitDispatcher::<minute>::new()),45 TimeUnit::Hour => Box::new(TimeUnitDispatcher::<hour>::new()),46 }47 }4849 fn preferred_precision(&self) -> usize {50 match self {51 TimeUnit::Second => 3,52 _ => 1,53 }54 }55}5657/// Supported information units58#[derive(Debug, Clone, Copy, PartialEq, Eq)]5960pub enum InformationUnit {61 Byte,62 KibiByte,63 MebiByte,64 GibiByte,65 TebiByte,66}6768impl IsUnit for InformationUnit {69 type Quantity = Information;7071 fn dispatch(&self) -> Box<dyn UnitImpl<Quantity = Information>> {72 match self {73 InformationUnit::Byte => Box::new(InformationUnitDispatcher::<byte>::new()),74 InformationUnit::KibiByte => Box::new(InformationUnitDispatcher::<kibibyte>::new()),75 InformationUnit::MebiByte => Box::new(InformationUnitDispatcher::<mebibyte>::new()),76 InformationUnit::GibiByte => Box::new(InformationUnitDispatcher::<gibibyte>::new()),77 InformationUnit::TebiByte => Box::new(InformationUnitDispatcher::<tebibyte>::new()),78 }79 }8081 fn preferred_precision(&self) -> usize {82 match self {83 InformationUnit::Byte => 0,84 _ => 1,85 }86 }87}8889pub trait UnitImpl {90 type Quantity;9192 fn short_name(&self) -> &'static str;93 fn format_value(&self, value: Self::Quantity, precision: usize) -> String;94}9596struct TimeUnitDispatcher<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> {97 u: PhantomData<U>,98}99100impl<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> TimeUnitDispatcher<U> {101 fn new() -> Self {102 TimeUnitDispatcher { u: PhantomData }103 }104}105106impl<U: uom::si::time::Unit + uom::Conversion<f64, T = f64>> UnitImpl for TimeUnitDispatcher<U> {107 type Quantity = Time;108109 fn short_name(&self) -> &'static str {110 U::abbreviation()111 }112113 fn format_value(&self, value: Time, precision: usize) -> String {114 format!("{value:.precision$}", value = value.get::<U>())115 }116}117118struct InformationUnitDispatcher<U: uom::si::information::Unit + uom::Conversion<f64, T = f64>> {119 u: PhantomData<U>,120}121122impl<U: uom::si::information::Unit + uom::Conversion<f64, T = f64>> InformationUnitDispatcher<U> {123 fn new() -> Self {124 InformationUnitDispatcher { u: PhantomData }125 }126}127128impl<U: uom::si::information::Unit + uom::Conversion<f64, T = f64>> UnitImpl129 for InformationUnitDispatcher<U>130{131 type Quantity = Information;132133 fn short_name(&self) -> &'static str {134 U::abbreviation()135 }136137 fn format_value(&self, value: Information, precision: usize) -> String {138 format!("{value:.precision$}", value = value.get::<U>())139 }140}141142#[test]143fn test_time_unit_short_name() {144 assert_eq!("s", TimeUnit::Second.short_name());145 assert_eq!("ms", TimeUnit::MilliSecond.short_name());146 assert_eq!("µs", TimeUnit::MicroSecond.short_name());147 assert_eq!("min", TimeUnit::Minute.short_name());148 assert_eq!("h", TimeUnit::Hour.short_name());149}150151// Note - the values are rounded when formatted.152#[test]153fn test_unit_format() {154 use crate::quantity::FormatQuantity;155156 let value = Time::new::<second>(123.456789);157 assert_eq!("123.457", value.format_value(TimeUnit::Second));158 assert_eq!("123456.8", value.format_value(TimeUnit::MilliSecond));159160 assert_eq!(161 "1234.6",162 Time::new::<second>(0.00123456).format_value(TimeUnit::MicroSecond)163 );164 assert_eq!("2.1", value.format_value(TimeUnit::Minute));165 assert_eq!("0.0", value.format_value(TimeUnit::Hour));166}
modified:src/timer/mod.rs+1 added
116 unmodified lines
117 let hardware_counters = Default::default();118119 Ok(Measurement {120 time_wall_clock,121 time_cpu: time_user + time_system,122 time_user,123 time_system,124 memory_peak_resident,125 hardware_counters,
3 unmodified lines
modified:src/cli.rs+49 added-70 removed
5 unmodified lines
6 builder::Styles,7 crate_version, Arg, ArgAction, ArgMatches, Command, ValueHint,8};910pub const DEFAULT_METRICS: &str = if cfg!(windows) {11 "time_wall_clock"12} else {13 "time_wall_clock,memory_peak_resident"14};1516pub fn get_cli_arguments<'a, I, T>(args: I) -> ArgMatches17where18 I: IntoIterator<Item = T>,19 T: Into<OsString> + Clone + 'a,
23 unmodified lines
43 .help("The command to benchmark. This can be the name of an executable, a command \44 line like \"grep -i todo\" or a shell command like \"sleep 0.5 && echo test\". \45 The latter requires a shell, which can be enabled via '-S' or '--shell=...'. \46 If multiple commands are given, hyperfine will show a \41 comparison of the respective runtimes.")47 comparison with the first command as the reference.")48 .required(true)49 .action(ArgAction::Append)50 .value_hint(ValueHint::CommandString)51 .value_parser(NonEmptyStringValueParser::new()),52 )53 .arg(54 Arg::new("metrics")55 .long("metrics")56 .value_name("PRESET|METRIC[:UNIT],…")57 .default_value("default")58 .hide_default_value(true)59 .help("Performance metrics to measure, in order.\n\n\60 This is either a preset name, or a comma-separated list of metrics with optional units. \61 The first metric is used for non-JSON exports, \62 JSON always includes all collected metrics.\n\n\63 Presets (use one on its own):\n \64 default Wall-clock time and peak RSS\n \65 time Wall-clock, CPU, user, and system time\n \66 all All available metrics\n\n\67 Presets use automatic units.\n\n\68 Metrics and optional units:\n \69 Time: time_wall_clock, time_cpu, time_user, time_system\n \70 Units: ns, us, ms, s, min, h\n \71 Memory: memory_peak_resident\n \72 Units: B, kB, MB, GB, TB, KiB, MiB, GiB, TiB\n \73 Counters: cpu_cycles, instructions, cache_references,\n \74 cache_misses, branch_misses\n \75 Units: count, k (thousand), M (million), B (billion)\n\n\76 Examples:\n \77 --metrics time_cpu,instructions\n \78 --metrics memory_peak_resident:MiB,time_wall_clock:ms\n \79 --metrics time"),80 )81 .arg(82 Arg::new("warmup")83 .long("warmup")84 .short('w')85 .value_name("NUM")
40 unmodified lines
126 .action(ArgAction::Set)127 .value_name("CMD")128 .value_hint(ValueHint::CommandString)129 .help(96 "Execute CMD before each set of timing runs. This is useful for \130 "Execute CMD before each set of benchmark runs. This is useful for \131 compiling your software with the provided parameters, or to do any \132 other work that should happen once before a series of benchmark runs, \133 not every time as would happen with the --prepare option."134 ),135 )136 .arg(103 Arg::new("reference")104 .long("reference")105 .action(ArgAction::Set)106 .value_name("CMD")107 .help(108 "The reference for the relative comparison of results. Without parameters, \109 CMD is run as a separate reference command. With --parameter-scan or \110 --parameter-list, CMD must exactly match one unique benchmark name as \111 shown in the output. If this is unset, results are compared with the \112 fastest command as reference."113 )114 )115 .arg(116 Arg::new("reference-name")117 .long("reference-name")118 .action(ArgAction::Set)119 .value_name("CMD")120 .help("Give a meaningful name to the reference command. This cannot be used \121 with parameterized benchmarks; use --command-name instead.")122 .requires("reference")123 )124 .arg(137 Arg::new("prepare")138 .long("prepare")139 .short('p')140 .action(ArgAction::Append)141 .num_args(1)142 .value_name("CMD")143 .value_hint(ValueHint::CommandString)144 .help(133 "Execute CMD before each timing run. This is useful for \145 "Execute CMD before each benchmark run. This is useful for \146 clearing disk caches, for example.\nThe --prepare option can \147 be specified once for all commands or multiple times, once for \148 each command. In the latter case, each preparation command will \149 be run prior to the corresponding benchmark command.",
7 unmodified lines
157 .num_args(1)158 .value_name("CMD")159 .value_hint(ValueHint::CommandString)160 .help(149 "Execute CMD after each timing run. This is useful for killing \161 "Execute CMD after each benchmark run. This is useful for killing \162 long-running processes started (e.g. a web server started in --prepare), \163 for example.\nThe --conclude option can be specified once for all \164 commands or multiple times, once for each command. In the latter case, \165 each conclude command will be run after the corresponding benchmark \
121 unmodified lines
287 the output of the tool.",288 ),289 )290 .arg(279 Arg::new("sort")280 .long("sort")281 .action(ArgAction::Set)282 .value_name("METHOD")283 .value_parser(["auto", "command", "mean-time"])284 .default_value("auto")285 .hide_default_value(true)286 .help(287 "Specify the sort order of the speed comparison summary and the exported tables for \288 markup formats (Markdown, AsciiDoc, org-mode):\n \289 * 'auto' (default): the speed comparison will be ordered by time and\n \290 the markup tables will be ordered by command (input order).\n \291 * 'command': order benchmarks in the way they were specified\n \292 * 'mean-time': order benchmarks by mean runtime\n"293 ),294 )295 .arg(296 Arg::new("time-unit")297 .long("time-unit")298 .short('u')299 .action(ArgAction::Set)300 .value_name("UNIT")301 .value_parser(["µs", "us", "microsecond", "microseconds", "ms", "millisecond", "milliseconds", "s", "second", "seconds", "min", "minute", "minutes", "h", "hour", "hours"])302 .help("Set the time unit to be used. If the option is not given, the time unit is determined automatically. \303 This option affects the standard output as well as all export formats except for CSV and JSON.\n\304 Possible values:\n \305 * 'µs', 'us', 'microsecond', 'microseconds'\n \306 * 'ms', 'millisecond', 'milliseconds'\n \307 * 's', 'second', 'seconds'\n \308 * 'min', 'minute', 'minutes'\n \309 * 'h', 'hour', 'hours'"),310 )311 .arg(291 Arg::new("export-asciidoc")292 .long("export-asciidoc")293 .action(ArgAction::Set)294 .value_name("FILE")295 .value_hint(ValueHint::FilePath)317 .help("Export the timing summary statistics as an AsciiDoc table to the given FILE. \318 The output time unit can be changed using the --time-unit option."),296 .help("Export the primary metric summary statistics as an AsciiDoc table to the given FILE. \297 The unit can be set with --metrics METRIC:UNIT."),298 )299 .arg(300 Arg::new("export-csv")301 .long("export-csv")302 .action(ArgAction::Set)303 .value_name("FILE")304 .value_hint(ValueHint::FilePath)326 .help("Export the timing summary statistics as CSV to the given FILE. If you need \327 the timing results for each individual run, use the JSON export format. \328 The output time unit is always seconds."),305 .help("Export the primary metric summary statistics as CSV to the given FILE. If you need \306 all metrics for each individual run, use the JSON export format. \307 Use the explicitly selected unit, or the base unit when unspecified."),308 )309 .arg(310 Arg::new("export-json")311 .long("export-json")312 .action(ArgAction::Set)313 .value_name("FILE")314 .value_hint(ValueHint::FilePath)336 .help("Export the timing summary statistics and timings of individual runs as JSON to the given FILE. \337 The output time unit is always seconds"),315 .help("Export all collected metrics and individual runs as JSON to the given FILE. \316 Values always use base units (seconds, bytes, counts)."),317 )318 .arg(319 Arg::new("export-markdown")320 .long("export-markdown")321 .action(ArgAction::Set)322 .value_name("FILE")323 .value_hint(ValueHint::FilePath)345 .help("Export the timing summary statistics as a Markdown table to the given FILE. \346 The output time unit can be changed using the --time-unit option."),324 .help("Export the primary metric summary statistics as a Markdown table to the given FILE. \325 The unit can be set with --metrics METRIC:UNIT."),326 )327 .arg(328 Arg::new("export-orgmode")329 .long("export-orgmode")330 .action(ArgAction::Set)331 .value_name("FILE")332 .value_hint(ValueHint::FilePath)354 .help("Export the timing summary statistics as an Emacs org-mode table to the given FILE. \355 The output time unit can be changed using the --time-unit option."),333 .help("Export the primary metric summary statistics as an Emacs org-mode table to the given FILE. \334 The unit can be set with --metrics METRIC:UNIT."),335 )336 .arg(337 Arg::new("show-output")338 .long("show-output")
84 unmodified lines
modified:src/command.rs+2 added-2 removed
255 unmodified lines
256 pub fn iter(&self) -> impl Iterator<Item = &Command<'a>> {257 self.0.iter()258 }259260 pub fn num_commands(&self, has_reference_command: bool) -> usize {261 self.0.len() + if has_reference_command { 1 } else { 0 }260 pub fn num_commands(&self) -> usize {261 self.0.len()262 }263264 /// Finds all the strings that appear multiple times in the input iterator, returning them in265 /// sorted order. If no string appears more than once, the result is an empty vector.
338 unmodified lines
modified:src/error.rs+2 added
39 unmodified lines
40}4142#[derive(Debug, Error)]43pub enum OptionsError<'a> {44 #[error("{0}")]45 InvalidMetrics(String),46 #[error(47 "Conflicting requirements for the number of runs (empty range, min is larger than max)"48 )]49 EmptyRunsRange,
17 unmodified lines
modified:src/main.rs+2 added-6 removed
19 unmodified lines
20pub mod cli;21pub mod command;22pub mod error;23pub mod export;24pub mod metric;25pub mod options;26pub mod outlier_detection;27pub mod output;28pub mod parameter;
10 unmodified lines
39 let mut options = Options::from_cli_arguments(&cli_arguments)?;40 let commands = Commands::from_cli_arguments(&cli_arguments)?;41 options.validate_against_command_list(&commands)?;4242 let export_manager = ExportManager::from_cli_arguments(43 &cli_arguments,44 options.time_unit,45 options.sort_order_exports,46 )?;43 let export_manager = ExportManager::from_cli_arguments(&cli_arguments, options.metrics[0])?;4445 let mut scheduler = Scheduler::new(&commands, &options, &export_manager);46 scheduler.run_benchmarks()?;50 scheduler.print_relative_speed_comparison()?;47 scheduler.final_export()?;4849 Ok(())50}
22 unmodified lines
added:src/metric.rs+505 added
1//! Metric selection, descriptive statistics, and display units.23use anyhow::{bail, ensure, Result};45use crate::benchmark::measurement::{Measurement, Measurements};6use crate::quantity::statistics::{max, mean, median, min, standard_deviation};7use crate::quantity::{byte, ratio, second, Ratio};89#[derive(Debug, Clone, Copy, PartialEq, Eq)]10pub enum Metric {11 TimeWallClock,12 TimeCpu,13 TimeUser,14 TimeSystem,15 MemoryPeakResident,16 CpuCycles,17 Instructions,18 CacheReferences,19 CacheMisses,20 BranchMisses,21}2223impl Metric {24 pub const ALL: [Self; 10] = [25 Self::TimeWallClock,26 Self::TimeCpu,27 Self::TimeUser,28 Self::TimeSystem,29 Self::MemoryPeakResident,30 Self::CpuCycles,31 Self::Instructions,32 Self::CacheReferences,33 Self::CacheMisses,34 Self::BranchMisses,35 ];3637 pub fn name(self) -> &'static str {38 match self {39 Self::TimeWallClock => "time_wall_clock",40 Self::TimeCpu => "time_cpu",41 Self::TimeUser => "time_user",42 Self::TimeSystem => "time_system",43 Self::MemoryPeakResident => "memory_peak_resident",44 Self::CpuCycles => "cpu_cycles",45 Self::Instructions => "instructions",46 Self::CacheReferences => "cache_references",47 Self::CacheMisses => "cache_misses",48 Self::BranchMisses => "branch_misses",49 }50 }5152 pub fn label(self) -> &'static str {53 match self {54 Self::TimeWallClock => "Wall Time",55 Self::TimeCpu => "CPU time",56 Self::TimeUser => "User time",57 Self::TimeSystem => "System time",58 Self::MemoryPeakResident => "Memory",59 Self::CpuCycles => "CPU cycles",60 Self::Instructions => "Instructions",61 Self::CacheReferences => "Cache references",62 Self::CacheMisses => "Cache misses",63 Self::BranchMisses => "Branch misses",64 }65 }6667 /// Extract a value in canonical units: seconds, bytes, or counts.68 pub fn value(self, measurement: &Measurement) -> Option<f64> {69 let counters = &measurement.hardware_counters;70 match self {71 Self::TimeWallClock => Some(measurement.time_wall_clock.get::<second>()),72 Self::TimeCpu => Some(measurement.time_cpu.get::<second>()),73 Self::TimeUser => Some(measurement.time_user.get::<second>()),74 Self::TimeSystem => Some(measurement.time_system.get::<second>()),75 Self::MemoryPeakResident => measurement.memory_peak_resident.map(|v| v.get::<byte>()),76 Self::CpuCycles => counters.cpu_cycles.map(|v| v as f64),77 Self::Instructions => counters.instructions.map(|v| v as f64),78 Self::CacheReferences => counters.cache_references.map(|v| v as f64),79 Self::CacheMisses => counters.cache_misses.map(|v| v as f64),80 Self::BranchMisses => counters.branch_misses.map(|v| v as f64),81 }82 }8384 pub fn is_time(self) -> bool {85 matches!(86 self,87 Self::TimeWallClock | Self::TimeCpu | Self::TimeUser | Self::TimeSystem88 )89 }9091 pub fn is_counter(self) -> bool {92 !self.is_time() && self != Self::MemoryPeakResident93 }9495 /// Reject known unsupported configurations before any commands execute.96 /// Availability that depends on permissions or hardware is checked after collection.97 pub fn ensure_available(self, shell: bool) -> Result<()> {98 if self.is_counter() {99 ensure!(100 !shell,101 "Metric '{}' is unavailable when a shell is enabled",102 self.name()103 );104 ensure!(105 cfg!(any(106 target_os = "macos",107 all(108 target_os = "linux",109 target_pointer_width = "64",110 any(111 target_arch = "aarch64",112 target_arch = "x86_64",113 target_arch = "riscv64",114 target_arch = "powerpc64",115 target_arch = "loongarch64"116 )117 )118 )),119 "Metric '{}' is unavailable on this platform",120 self.name()121 );122 ensure!(123 !cfg!(target_os = "macos") || matches!(self, Self::CpuCycles | Self::Instructions),124 "Metric '{}' is unavailable on macOS",125 self.name()126 );127 }128 ensure!(129 !cfg!(windows) || self != Self::MemoryPeakResident,130 "Metric '{}' is unavailable on Windows",131 self.name()132 );133 Ok(())134 }135136 pub fn base_unit(self) -> Unit {137 if self.is_time() {138 Unit::new("s", 1.0)139 } else if self.is_counter() {140 Unit::new("count", 1.0)141 } else {142 Unit::new("B", 1.0)143 }144 }145146 fn units(self) -> &'static [Unit] {147 if self.is_time() {148 TIME_UNITS149 } else if self.is_counter() {150 COUNT_UNITS151 } else {152 MEMORY_UNITS153 }154 }155156 /// Require complete coverage so different metrics describe the same runs.157 pub fn summarize(self, measurements: &Measurements) -> Option<Stats> {158 let values = measurements159 .measurements160 .iter()161 .map(|measurement| self.value(measurement))162 .collect::<Option<Vec<_>>>()?;163 if values.is_empty() {164 return None;165 }166 Some(Stats {167 count: values.len(),168 mean: mean(values.iter().copied()),169 stddev: (values.len() > 1).then(|| {170 standard_deviation(values.iter().map(|&v| Ratio::new::<ratio>(v))).get::<ratio>()171 }),172 median: median(values.iter().copied()),173 min: min(values.iter().copied()),174 max: max(values.iter().copied()),175 })176 }177}178179#[derive(Debug, Clone, Copy, PartialEq)]180pub struct MetricSelection {181 pub metric: Metric,182 pub unit: Option<Unit>,183}184185impl Default for MetricSelection {186 fn default() -> Self {187 Self {188 metric: Metric::TimeWallClock,189 unit: None,190 }191 }192}193194impl MetricSelection {195 /// Parse an ordered, nonempty list of `METRIC[:UNIT]` selections.196 pub fn parse_list(input: &str) -> Result<Vec<Self>> {197 let mut selections = Vec::new();198 for item in input.split(',') {199 let (name, unit_name) = match item.split_once(':') {200 Some((name, unit)) => (name, Some(unit)),201 None => (item, None),202 };203 let metric = match Metric::ALL.iter().copied().find(|m| m.name() == name) {204 Some(metric) => metric,205 None => bail!(206 "Unknown metric '{name}'. Expected one of: {}",207 Metric::ALL.map(Metric::name).join(", ")208 ),209 };210 if selections211 .iter()212 .any(|selection: &Self| selection.metric == metric)213 {214 bail!("Metric '{name}' was selected more than once");215 }216 let unit = match unit_name {217 None => None,218 Some(unit_name) => {219 // Accept an ASCII spelling for microseconds as well.220 let unit_name = if unit_name == "us" { "µs" } else { unit_name };221 match metric.units().iter().find(|unit| unit.symbol == unit_name) {222 Some(unit) => Some(*unit),223 None => bail!(224 "Unit '{unit_name}' is not valid for metric '{name}'. Expected one of: {}",225 metric.units().iter().map(|u| u.symbol).collect::<Vec<_>>().join(", ")226 ),227 }228 }229 };230 selections.push(Self { metric, unit });231 }232 Ok(selections)233 }234235 pub fn display_unit(self, mean: f64) -> Unit {236 if let Some(unit) = self.unit {237 return unit;238 }239 if mean == 0.0 {240 return self.metric.base_unit();241 }242 let units = if self.metric == Metric::MemoryPeakResident {243 BINARY_MEMORY_UNITS244 } else {245 self.metric.units()246 };247 units248 .iter()249 .rev()250 .find(|unit| mean.abs() >= unit.scale)251 .copied()252 .unwrap_or(units[0])253 }254255 /// CSV never automatically scales values.256 pub fn csv_unit(self) -> Unit {257 self.unit.unwrap_or_else(|| self.metric.base_unit())258 }259}260261#[derive(Debug, Clone, Copy, PartialEq)]262pub struct Unit {263 pub symbol: &'static str,264 /// The number of canonical units in this unit (e.g. 1e9 for a billion).265 pub scale: f64,266}267268impl Unit {269 const fn new(symbol: &'static str, scale: f64) -> Self {270 Self { symbol, scale }271 }272273 pub fn format(self, value: f64) -> String {274 let value = self.format_value(value);275 if self.symbol == "count" {276 value277 } else {278 format!("{value} {}", self.symbol)279 }280 }281282 pub fn format_value(self, value: f64) -> String {283 let precision = if self.symbol == "s" { 3 } else { 1 };284 format!("{:.precision$}", value / self.scale)285 }286}287288const TIME_UNITS: &[Unit] = &[289 Unit::new("ns", 1e-9),290 Unit::new("µs", 1e-6),291 Unit::new("ms", 1e-3),292 Unit::new("s", 1.0),293 Unit::new("min", 60.0),294 Unit::new("h", 3600.0),295];296297const BINARY_MEMORY_UNITS: &[Unit] = &[298 Unit::new("B", 1.0),299 Unit::new("KiB", 1024.0),300 Unit::new("MiB", 1_048_576.0),301 Unit::new("GiB", 1_073_741_824.0),302 Unit::new("TiB", 1_099_511_627_776.0),303];304305const MEMORY_UNITS: &[Unit] = &[306 Unit::new("B", 1.0),307 Unit::new("kB", 1e3),308 Unit::new("MB", 1e6),309 Unit::new("GB", 1e9),310 Unit::new("TB", 1e12),311 Unit::new("KiB", 1024.0),312 Unit::new("MiB", 1_048_576.0),313 Unit::new("GiB", 1_073_741_824.0),314 Unit::new("TiB", 1_099_511_627_776.0),315];316317const COUNT_UNITS: &[Unit] = &[318 Unit::new("count", 1.0),319 Unit::new("k", 1e3),320 Unit::new("M", 1e6),321 Unit::new("B", 1e9),322];323324#[derive(Debug, Clone, Copy)]325pub struct Stats {326 pub count: usize,327 pub mean: f64,328 pub stddev: Option<f64>,329 pub median: f64,330 pub min: f64,331 pub max: f64,332}333334impl Stats {335 pub fn change_from(&self, reference: &Self) -> Option<f64> {336 (reference.mean != 0.0).then(|| 100.0 * (self.mean / reference.mean - 1.0))337 }338339 pub fn format_change_from(&self, reference: &Self) -> String {340 let Some(change) = self.change_from(reference) else {341 return "N/A".to_owned();342 };343 let mut formatted = format!("{change:+.1}%");344 if formatted == "+0.0%" || formatted == "-0.0%" {345 formatted = "0.0%".to_owned();346 }347 formatted348 }349350 pub fn format_factor_from(&self, reference: &Self, metric: Metric) -> String {351 if reference.mean > 0.0352 && (self.mean >= 1.3 * reference.mean || self.mean <= 0.7 * reference.mean)353 {354 let decrease = self.mean < reference.mean;355 let factor = if decrease {356 reference.mean / self.mean357 } else {358 self.mean / reference.mean359 };360 let direction = match (metric.is_time(), decrease) {361 (true, true) => "faster",362 (true, false) => "slower",363 (false, true) => "less",364 (false, false) => "more",365 };366 let factor = if factor.is_infinite() {367 "∞".to_owned()368 } else {369 format!("{factor:.1}")370 };371 format!("({factor}x {direction})")372 } else {373 String::new()374 }375 }376}377378#[cfg(test)]379mod tests {380 use super::*;381 use crate::quantity::{Information, Time};382383 #[test]384 fn large_changes_include_factors() {385 let reference = Stats {386 count: 1,387 mean: 100.0,388 stddev: None,389 median: 100.0,390 min: 100.0,391 max: 100.0,392 };393 for (mean, metric, expected) in [394 (130.0, Metric::TimeWallClock, "+30.0% (1.3x slower)"),395 (70.0, Metric::TimeCpu, "-30.0% (1.4x faster)"),396 (10.0, Metric::Instructions, "-90.0% (10.0x less)"),397 (1000.0, Metric::MemoryPeakResident, "+900.0% (10.0x more)"),398 (129.99, Metric::TimeWallClock, "+30.0%"),399 (70.01, Metric::Instructions, "-30.0%"),400 (100.0, Metric::Instructions, "0.0%"),401 (0.0, Metric::Instructions, "-100.0% (∞x less)"),402 ] {403 let stats = Stats { mean, ..reference };404 let (percentage, factor) = expected405 .split_once(" (")406 .map_or((expected, String::new()), |(p, f)| (p, format!("({f}")));407 assert_eq!(stats.format_change_from(&reference), percentage);408 assert_eq!(stats.format_factor_from(&reference, metric), factor);409 }410 let zero = Stats {411 mean: 0.0,412 ..reference413 };414 assert_eq!(reference.format_change_from(&zero), "N/A");415 }416417 #[test]418 fn cpu_time_statistics_use_per_run_totals() {419 let measurements = Measurements::new(420 [(1.0, 3.0), (3.0, 1.0)]421 .iter()422 .map(|&(user, system)| Measurement {423 time_cpu: Time::new::<second>(user + system),424 time_user: Time::new::<second>(user),425 time_system: Time::new::<second>(system),426 ..Measurement::default()427 })428 .collect(),429 );430 let selection = MetricSelection::parse_list("time_cpu:ms").unwrap()[0];431 let stats = selection.metric.summarize(&measurements).unwrap();432 assert_eq!(selection.csv_unit().format(stats.mean), "4000.0 ms");433 // User and system time vary, but their per-run total is constant.434 assert_eq!(stats.stddev, Some(0.0));435 assert_eq!(stats.min, 4.0);436 assert_eq!(stats.max, 4.0);437 let json = serde_json::to_value(&measurements).unwrap();438 for sample in json["measurements"].as_array().unwrap() {439 assert_eq!(sample["time_cpu"]["value"], 4.0);440 assert_eq!(sample["time_cpu"]["unit"], "second");441 }442 }443444 #[test]445 fn selection_units_and_validation() {446 let selections = MetricSelection::parse_list(447 "instructions:B,memory_peak_resident:B,time_wall_clock:ms,time_user:us",448 )449 .unwrap();450 assert_eq!(selections[0].csv_unit().scale, 1e9);451 assert_eq!(selections[1].csv_unit().scale, 1.0);452 assert_eq!(selections[2].csv_unit().format(0.125), "125.0 ms");453 assert_eq!(selections[3].csv_unit().symbol, "µs");454455 let instructions = MetricSelection::parse_list("instructions").unwrap()[0];456 assert_eq!(instructions.csv_unit().symbol, "count");457 assert_eq!(458 instructions.display_unit(143.2e9).format(143.2e9),459 "143.2 B"460 );461 for invalid in [462 "",463 "unknown",464 "time_wall_clock,",465 "instructions,instructions:M",466 "instructions:MiB",467 "memory_peak_resident:ms",468 "time_wall_clock:",469 ] {470 assert!(MetricSelection::parse_list(invalid).is_err(), "{}", invalid);471 }472 }473474 #[test]475 fn summaries_require_complete_samples() {476 let mut measurements = Measurements::new(vec![Measurement {477 memory_peak_resident: Some(Information::new::<byte>(10.0)),478 ..Measurement::default()479 }]);480 let single = Metric::MemoryPeakResident.summarize(&measurements).unwrap();481 assert_eq!(single.stddev, None);482 measurements.push(Measurement::default());483 assert!(Metric::MemoryPeakResident484 .summarize(&measurements)485 .is_none());486 measurements.measurements[1].memory_peak_resident = Some(Information::new::<byte>(30.0));487 let stats = Metric::MemoryPeakResident.summarize(&measurements).unwrap();488 assert_eq!(stats.mean, 20.0);489 assert_eq!(stats.change_from(&single), Some(100.0));490 assert_eq!(stats.format_change_from(&single), "+100.0%");491 assert_eq!(single.format_change_from(&stats), "-50.0%");492 assert_eq!(493 Stats {494 mean: 9.999,495 ..single496 }497 .format_change_from(&single),498 "0.0%"499 );500 approx::assert_relative_eq!(stats.stddev.unwrap(), 200.0_f64.sqrt());501 let zero = Metric::TimeWallClock.summarize(&measurements).unwrap();502 assert_eq!(zero.change_from(&zero), None);503 assert_eq!(zero.format_change_from(&zero), "N/A");504 }505}
modified:src/options.rs+54 added-90 removed
2 unmodified lines
3use std::path::PathBuf;4use std::process::{Command, Stdio};5use std::{cmp, env, fmt, io};67use anyhow::{bail, ensure};7use anyhow::ensure;8use clap::ArgMatches;910use crate::command::Commands;11use crate::error::OptionsError;12use crate::metric::{Metric, MetricSelection};12use crate::quantity::{second, Time, TimeUnit};13use crate::quantity::{second, Time};1415use anyhow::Result;1617#[cfg(not(windows))]
79 unmodified lines
97 /// Disable all the output98 Disabled,99}100100#[derive(Debug, Clone, Copy, PartialEq, Eq)]101pub enum SortOrder {102 Command,103 MeanTime,104}105101/// Bounds for the number of benchmark runs102pub struct RunBounds {103 /// Minimum number of benchmark runs104 pub min: u64,
91 unmodified lines
196197 /// Whether or not to ignore non-zero exit codes198 pub command_failure_action: CmdFailureAction,199205 // Standalone reference command, cleared when an existing benchmark is selected.206 pub reference_command: Option<String>,207208 // Name of the reference command209 pub reference_name: Option<String>,210211 // Index of the reference in the benchmark sequence, if any.212 pub reference_index: Option<usize>,213214 /// Command(s) to run before each timing run200 /// Command(s) to run before each benchmark run201 pub preparation_command: Option<Vec<String>>,202217 /// Command(s) to run after each timing run203 /// Command(s) to run after each benchmark run204 pub conclusion_command: Option<Vec<String>>,205220 /// Command to run before each *batch* of timing runs, i.e. before each individual benchmark206 /// Command to run before each *batch* of benchmark runs, i.e. before each individual benchmark207 pub setup_command: Option<String>,208223 /// Command to run after each *batch* of timing runs, i.e. after each individual benchmark209 /// Command to run after each *batch* of benchmark runs, i.e. after each individual benchmark210 pub cleanup_command: Option<String>,211212 /// What color mode to use for the terminal output213 pub output_style: OutputStyleOption,214229 /// How to order benchmarks in the relative speed comparison230 pub sort_order_speed_comparison: SortOrder,231232 /// How to order benchmarks in the markup format exports233 pub sort_order_exports: SortOrder,234215 /// Determines how we run commands216 pub executor_kind: ExecutorKind,217218 /// Where input to the benchmarked command comes from
1 unmodified line
220221 /// What to do with the output of the benchmarked commands222 pub command_output_policies: Vec<CommandOutputPolicy>,223244 /// Which time unit to use when displaying results245 pub time_unit: Option<TimeUnit>,224 /// Displayed metrics, with the primary metric first.225 pub metrics: Vec<MetricSelection>,226227 /// The `all` preset displays only metrics with complete measurements.228 pub skip_unavailable_metrics: bool,229}230231impl Default for Options {232 fn default() -> Options {
1 unmodified line
234 run_bounds: RunBounds::default(),235 warmup_count: 0,236 min_benchmarking_time: Time::new::<second>(3.0),237 command_failure_action: CmdFailureAction::RaiseError,255 reference_command: None,256 reference_name: None,257 reference_index: None,238 preparation_command: None,239 conclusion_command: None,240 setup_command: None,241 cleanup_command: None,242 output_style: OutputStyleOption::Full,263 sort_order_speed_comparison: SortOrder::MeanTime,264 sort_order_exports: SortOrder::Command,243 executor_kind: ExecutorKind::default(),244 command_output_policies: vec![CommandOutputPolicy::Null],267 time_unit: None,245 metrics: MetricSelection::parse_list(crate::cli::DEFAULT_METRICS)246 .expect("valid default metrics"),247 skip_unavailable_metrics: false,248 command_input_policy: CommandInputPolicy::Null,249 }250 }251}
34 unmodified lines
286 };287288 options.setup_command = matches.get_one::<String>("setup").map(String::from);289310 options.reference_command = matches.get_one::<String>("reference").map(String::from);311 options.reference_name = matches312 .get_one::<String>("reference-name")313 .map(String::from);314290 options.preparation_command = matches291 .get_many::<String>("prepare")292 .map(|values| values.map(String::from).collect::<Vec<String>>());293
63 unmodified lines
357 }358 OutputStyleOption::Disabled => {}359 };360386 (387 options.sort_order_speed_comparison,388 options.sort_order_exports,389 ) = match matches.get_one::<String>("sort").map(|s| s.as_str()) {390 None | Some("auto") => (SortOrder::MeanTime, SortOrder::Command),391 Some("command") => (SortOrder::Command, SortOrder::Command),392 Some("mean-time") => (SortOrder::MeanTime, SortOrder::MeanTime),393 Some(_) => unreachable!("Unknown sort order"),394 };395361 options.executor_kind = if matches.get_flag("no-shell") {362 ExecutorKind::Raw363 } else if matches.get_flag("default-shell") {364 ExecutorKind::Shell(Shell::platform_default())
29 unmodified lines
394 }395 };396 }397433 options.time_unit = match matches.get_one::<String>("time-unit").map(|s| s.as_str()) {434 Some("µs" | "us" | "microsecond" | "microseconds") => Some(TimeUnit::MicroSecond),435 Some("ms" | "millisecond" | "milliseconds") => Some(TimeUnit::MilliSecond),436 Some("s" | "second" | "seconds") => Some(TimeUnit::Second),437 Some("min" | "minute" | "minutes") => Some(TimeUnit::Minute),438 Some("h" | "hour" | "hours") => Some(TimeUnit::Hour),439 _ => None,440 };398 match matches.get_one::<String>("metrics").unwrap().as_str() {399 "default" => {}400 "time" => {401 options.metrics = [402 Metric::TimeWallClock,403 Metric::TimeCpu,404 Metric::TimeUser,405 Metric::TimeSystem,406 ]407 .map(|metric| MetricSelection { metric, unit: None })408 .to_vec();409 }410 "all" => {411 let shell = matches!(412 options.executor_kind,413 ExecutorKind::Shell(_) | ExecutorKind::Mock(Some(_))414 );415 options.metrics = Metric::ALL416 .iter()417 .copied()418 .filter(|metric| metric.ensure_available(shell).is_ok())419 .map(|metric| MetricSelection { metric, unit: None })420 .collect();421 options.skip_unavailable_metrics = true;422 }423 list => {424 options.metrics = MetricSelection::parse_list(list)425 .map_err(|error| OptionsError::InvalidMetrics(error.to_string()))?;426 }427 }428429 if let Some(time) = matches.get_one::<String>("min-benchmarking-time") {430 options.min_benchmarking_time = Time::new::<second>(431 time.parse::<f64>()
20 unmodified lines
452 Ok(options)453 }454455 pub fn validate_against_command_list(&mut self, commands: &Commands) -> Result<()> {469 if let Some(reference) = &self.reference_command {470 if commands471 .iter()472 .next()473 .is_some_and(|command| !command.get_parameters().is_empty())474 {475 ensure!(476 self.reference_name.is_none(),477 "--reference-name cannot be used with a parameterized reference; use --command-name to name the benchmark"478 );479 let mut matches = commands480 .iter()481 .enumerate()482 .filter(|(_, command)| command.get_name_with_unused_parameters() == *reference);483 let Some((index, _)) = matches.next() else {484 bail!(485 "Reference '{reference}' does not match any parameterized benchmark. Use its full displayed benchmark name."486 );487 };488 ensure!(489 matches.next().is_none(),490 "Reference '{reference}' matches multiple parameterized benchmarks. Use --command-name to give them unique names."491 );492 self.reference_index = Some(index);493 self.reference_command = None;494 } else {495 self.reference_index = Some(0);456 if !matches!(self.executor_kind, ExecutorKind::Mock(_)) {457 for selection in &self.metrics {458 selection459 .metric460 .ensure_available(matches!(self.executor_kind, ExecutorKind::Shell(_)))?;461 }462 }498 let has_reference_command = self.reference_command.is_some();499 let num_commands = commands.num_commands(has_reference_command);463 let num_commands = commands.num_commands();464465 if let Some(preparation_command) = &self.preparation_command {466 ensure!(467 preparation_command.len() <= 1 || num_commands == preparation_command.len(),468 "The '--prepare' option has to be provided just once or N times, where N={num_commands} is the \505 number of benchmark commands (including a potential reference)."469 number of benchmark commands."470 );471 }472473 if let Some(conclusion_command) = &self.conclusion_command {474 ensure!(475 conclusion_command.len() <= 1 || num_commands == conclusion_command.len(),476 "The '--conclude' option has to be provided just once or N times, where N={num_commands} is the \513 number of benchmark commands (including a potential reference)."477 number of benchmark commands."478 );479 }480481 if self.command_output_policies.len() == 1 {
2 unmodified lines
484 } else {485 ensure!(486 self.command_output_policies.len() == num_commands,487 "The '--output' option has to be provided just once or N times, where N={num_commands} is the \524 number of benchmark commands (including a potential reference)."488 number of benchmark commands."489 );490 }491492 Ok(())
46 unmodified lines
modified:tests/snapshots/integration_tests__json_export_basic.snap+56 added-21 removed
1---2source: tests/integration_tests.rs3assertion_line: 12784info:5 program: hyperfine6 args:7 - "--debug-mode"8 - "--style=none"9 - "--export-json=-"10 - "--runs=2"11 - "--warmup=1"11 - "--reference-name=one second"12 - "--reference=sleep 1"12 - "--command-name=one second"13 - sleep 114 - "--command-name=sleep 2"15 - sleep 216---17success: true
9 unmodified lines
27 "os": "[os]",28 "architecture": "[architecture]"29 }30 },31 "primary_metric": "time_wall_clock",32 "results": [33 {34 "command": "sleep 1",35 "name": "one second",
2 unmodified lines
38 "time_wall_clock": {39 "value": 1.0,40 "unit": "second"41 },42 "time_cpu": {43 "value": 0.0,44 "unit": "second"45 },46 "time_user": {47 "value": 0.0,48 "unit": "second"49 },
11 unmodified lines
61 "time_wall_clock": {62 "value": 1.0,63 "unit": "second"64 },65 "time_cpu": {66 "value": 0.0,67 "unit": "second"68 },69 "time_user": {70 "value": 0.0,71 "unit": "second"72 },
7 unmodified lines
80 },81 "exit_code": 082 }83 ],74 "is_reference": true,84 "summary": {76 "time_wall_clock": {77 "unit": "second",85 "memory_peak_resident": {86 "unit": "byte",87 "count": 2,79 "mean": 1.0,88 "mean": 0.0,89 "stddev": 0.0,81 "median": 1.0,82 "min": 1.0,83 "max": 1.090 "median": 0.0,91 "min": 0.0,92 "max": 0.093 },85 "time_user": {94 "time_cpu": {95 "unit": "second",96 "count": 2,97 "mean": 0.0,98 "stddev": 0.0,
9 unmodified lines
108 "median": 0.0,109 "min": 0.0,110 "max": 0.0111 },103 "memory_peak_resident": {104 "unit": "byte",112 "time_user": {113 "unit": "second",114 "count": 2,115 "mean": 0.0,116 "stddev": 0.0,117 "median": 0.0,118 "min": 0.0,119 "max": 0.0120 },121 "time_wall_clock": {122 "unit": "second",123 "count": 2,124 "mean": 1.0,125 "stddev": 0.0,126 "median": 1.0,127 "min": 1.0,128 "max": 1.0129 }130 }131 },132 {
3 unmodified lines
136 "time_wall_clock": {137 "value": 2.0,138 "unit": "second"139 },140 "time_cpu": {141 "value": 0.0,142 "unit": "second"143 },144 "time_user": {145 "value": 0.0,146 "unit": "second"147 },
11 unmodified lines
159 "time_wall_clock": {160 "value": 2.0,161 "unit": "second"162 },163 "time_cpu": {164 "value": 0.0,165 "unit": "second"166 },167 "time_user": {168 "value": 0.0,169 "unit": "second"170 },
8 unmodified lines
179 "exit_code": 0180 }181 ],182 "summary": {157 "time_wall_clock": {158 "unit": "second",183 "memory_peak_resident": {184 "unit": "byte",185 "count": 2,160 "mean": 2.0,186 "mean": 0.0,187 "stddev": 0.0,162 "median": 2.0,163 "min": 2.0,164 "max": 2.0188 "median": 0.0,189 "min": 0.0,190 "max": 0.0191 },166 "time_user": {192 "time_cpu": {193 "unit": "second",194 "count": 2,195 "mean": 0.0,196 "stddev": 0.0,
9 unmodified lines
206 "median": 0.0,207 "min": 0.0,208 "max": 0.0209 },184 "memory_peak_resident": {185 "unit": "byte",210 "time_user": {211 "unit": "second",212 "count": 2,213 "mean": 0.0,214 "stddev": 0.0,215 "median": 0.0,216 "min": 0.0,217 "max": 0.0218 },219 "time_wall_clock": {220 "unit": "second",221 "count": 2,222 "mean": 2.0,223 "stddev": 0.0,224 "median": 2.0,225 "min": 2.0,226 "max": 2.0227 }228 }229 }230 ]
4 unmodified lines
modified:tests/snapshots/integration_tests__json_export_parameterized_with_reference.snap+54 added-20 removed
1---2source: tests/integration_tests.rs3assertion_line: 13054info:5 program: hyperfine6 args:7 - "--debug-mode"
3 unmodified lines
11 - "-L"12 - duration13 - "1,2"14 - "--command-name=sleep for {duration} seconds"14 - "--reference=sleep for 2 seconds"15 - "sleep {duration}"16---17success: true18exit_code: 0
8 unmodified lines
27 "os": "[os]",28 "architecture": "[architecture]"29 }30 },31 "primary_metric": "time_wall_clock",32 "results": [33 {34 "command": "sleep 1",35 "name": "sleep for 1 seconds",
2 unmodified lines
38 "time_wall_clock": {39 "value": 1.0,40 "unit": "second"41 },42 "time_cpu": {43 "value": 0.0,44 "unit": "second"45 },46 "time_user": {47 "value": 0.0,48 "unit": "second"49 },
11 unmodified lines
61 "time_wall_clock": {62 "value": 1.0,63 "unit": "second"64 },65 "time_cpu": {66 "value": 0.0,67 "unit": "second"68 },69 "time_user": {70 "value": 0.0,71 "unit": "second"72 },
13 unmodified lines
86 "value": "1"87 }88 },89 "summary": {81 "time_wall_clock": {82 "unit": "second",90 "memory_peak_resident": {91 "unit": "byte",92 "count": 2,84 "mean": 1.0,93 "mean": 0.0,94 "stddev": 0.0,86 "median": 1.0,87 "min": 1.0,88 "max": 1.095 "median": 0.0,96 "min": 0.0,97 "max": 0.098 },90 "time_user": {99 "time_cpu": {100 "unit": "second",101 "count": 2,102 "mean": 0.0,103 "stddev": 0.0,
9 unmodified lines
113 "median": 0.0,114 "min": 0.0,115 "max": 0.0116 },108 "memory_peak_resident": {109 "unit": "byte",117 "time_user": {118 "unit": "second",119 "count": 2,120 "mean": 0.0,121 "stddev": 0.0,122 "median": 0.0,123 "min": 0.0,124 "max": 0.0125 },126 "time_wall_clock": {127 "unit": "second",128 "count": 2,129 "mean": 1.0,130 "stddev": 0.0,131 "median": 1.0,132 "min": 1.0,133 "max": 1.0134 }135 }136 },137 {
4 unmodified lines
142 "time_wall_clock": {143 "value": 2.0,144 "unit": "second"145 },146 "time_cpu": {147 "value": 0.0,148 "unit": "second"149 },150 "time_user": {151 "value": 0.0,152 "unit": "second"153 },
11 unmodified lines
165 "time_wall_clock": {166 "value": 2.0,167 "unit": "second"168 },169 "time_cpu": {170 "value": 0.0,171 "unit": "second"172 },173 "time_user": {174 "value": 0.0,175 "unit": "second"176 },
12 unmodified lines
189 "duration": {190 "value": "2"191 }192 },167 "is_reference": true,193 "summary": {169 "time_wall_clock": {170 "unit": "second",194 "memory_peak_resident": {195 "unit": "byte",196 "count": 2,172 "mean": 2.0,197 "mean": 0.0,198 "stddev": 0.0,174 "median": 2.0,175 "min": 2.0,176 "max": 2.0199 "median": 0.0,200 "min": 0.0,201 "max": 0.0202 },178 "time_user": {203 "time_cpu": {204 "unit": "second",205 "count": 2,206 "mean": 0.0,207 "stddev": 0.0,
9 unmodified lines
217 "median": 0.0,218 "min": 0.0,219 "max": 0.0220 },196 "memory_peak_resident": {197 "unit": "byte",221 "time_user": {222 "unit": "second",223 "count": 2,224 "mean": 0.0,225 "stddev": 0.0,226 "median": 0.0,227 "min": 0.0,228 "max": 0.0229 },230 "time_wall_clock": {231 "unit": "second",232 "count": 2,233 "mean": 2.0,234 "stddev": 0.0,235 "median": 2.0,236 "min": 2.0,237 "max": 2.0238 }239 }240 }241 ]
4 unmodified lines
modified:tests/snapshots/integration_tests__json_export_single_run.snap+24 added-9 removed
1---2source: tests/integration_tests.rs3assertion_line: 12944info:5 program: hyperfine6 args:7 - "--debug-mode"
15 unmodified lines
23 "os": "[os]",24 "architecture": "[architecture]"25 }26 },27 "primary_metric": "time_wall_clock",28 "results": [29 {30 "command": "sleep 1",31 "measurements": [
1 unmodified line
33 "time_wall_clock": {34 "value": 1.0,35 "unit": "second"36 },37 "time_cpu": {38 "value": 0.0,39 "unit": "second"40 },41 "time_user": {42 "value": 0.0,43 "unit": "second"44 },
8 unmodified lines
53 "exit_code": 054 }55 ],56 "summary": {51 "time_wall_clock": {52 "unit": "second",57 "memory_peak_resident": {58 "unit": "byte",59 "count": 1,54 "mean": 1.0,60 "mean": 0.0,61 "stddev": null,56 "median": 1.0,57 "min": 1.0,58 "max": 1.062 "median": 0.0,63 "min": 0.0,64 "max": 0.065 },60 "time_user": {66 "time_cpu": {67 "unit": "second",68 "count": 1,69 "mean": 0.0,70 "stddev": null,
9 unmodified lines
80 "median": 0.0,81 "min": 0.0,82 "max": 0.083 },78 "memory_peak_resident": {79 "unit": "byte",84 "time_user": {85 "unit": "second",86 "count": 1,87 "mean": 0.0,88 "stddev": null,89 "median": 0.0,90 "min": 0.0,91 "max": 0.092 },93 "time_wall_clock": {94 "unit": "second",95 "count": 1,96 "mean": 1.0,97 "stddev": null,98 "median": 1.0,99 "min": 1.0,100 "max": 1.0101 }102 }103 }104 ]
4 unmodified lines
modified:tests/execution_order_tests.rs+6 added-11 removed
54 unmodified lines
55 self.arg("--prepare");56 self.command(output)57 }5859 fn reference(&mut self, output: &str) -> &mut Self {60 self.arg("--reference");61 self.command(output)62 }6359 fn conclude(&mut self, output: &str) -> &mut Self {60 self.arg("--conclude");61 self.command(output)62 }
304 unmodified lines
367 .run();368}369370#[test]376fn reference_is_executed_first() {371fn commands_execute_in_input_order() {372 ExecutionOrderTest::new()373 .arg("--runs=1")379 .reference("reference")374 .command("reference")375 .command("command 1")376 .command("command 2")377 .expect_output("reference")378 .expect_output("command 1")
1 unmodified line
380 .run();381}382383#[test]389fn reference_is_executed_separately_from_commands() {384fn repeated_commands_execute_separately() {385 ExecutionOrderTest::new()386 .arg("--runs=1")392 .reference("command 1")387 .command("command 1")388 .command("command 1")389 .command("command 2")390 .expect_output("command 1")391 .expect_output("command 1")392 .expect_output("command 2")
6 unmodified lines
399 .arg("--warmup=1")400 .arg("--runs=2")401 .setup("setup")402 .prepare("prepare")408 .reference("reference")403 .command("reference")404 .command("command1")405 .command("command2")406 .conclude("conclude")407 .cleanup("cleanup")
83 unmodified lines
491 .arg("--runs=2")492 .setup("setup")493 .cleanup("cleanup")494 .prepare("prepareref")500 .reference("reference")495 .command("reference")496 .conclude("concluderef")497 .prepare("prepare1")498 .command("command1")499 .conclude("conclude1")
41 unmodified lines
modified:tests/integration_tests.rs+179 added-249 removed
109 unmodified lines
110}111112#[test]113fn min_runs_of_one_still_performs_one_run() {114 hyperfine_debug()114 let _settings = snapshot_settings().bind_to_scope();115 assert_cmd_snapshot!(hyperfine_debug()116 .arg("--style=basic")117 .arg("--metrics=time_wall_clock")118 .arg("--min-runs=1")119 .arg("--warmup=0")117 .arg("sleep 4")118 .assert()119 .success()120 .stdout(predicate::str::contains("Time (abs ≡)"));120 .arg("sleep 4"), @"121 success: true122 exit_code: 0123 ----- stdout -----124 Benchmark 1: sleep 4 (1 run)125 Value126 Wall Time 4.000 s127128129 ----- stderr -----130 ");131}132133#[test]134fn can_run_commands_without_a_shell() {
33 unmodified lines
168 .arg("--runs=1")169 .arg("--prepare=echo ref")170 .arg("--prepare=echo a")171 .arg("--prepare=echo b")162 .arg("--reference=echo ref")172 .arg("echo ref")173 .arg("echo a")174 .arg("echo b")175 .assert()176 .success();
14 unmodified lines
191 hyperfine()192 .arg("--runs=1")193 .arg("--prepare=echo a")194 .arg("--prepare=echo b")185 .arg("--reference=echo ref")195 .arg("echo ref")196 .arg("echo a")197 .arg("echo b")198 .assert()199 .failure()
17 unmodified lines
217 .arg("--runs=1")218 .arg("--conclude=echo ref")219 .arg("--conclude=echo a")220 .arg("--conclude=echo b")211 .arg("--reference=echo ref")221 .arg("echo ref")222 .arg("echo a")223 .arg("echo b")224 .assert()225 .success();
14 unmodified lines
240 hyperfine()241 .arg("--runs=1")242 .arg("--conclude=echo a")243 .arg("--conclude=echo b")234 .arg("--reference=echo ref")244 .arg("echo ref")245 .arg("echo a")246 .arg("echo b")247 .assert()248 .failure()
269 unmodified lines
518 hyperfine_debug()519 .arg("sleep 1.234")520 .assert()521 .success()512 .stdout(predicate::str::contains("Time (mean ± σ): 1.234 s ±"));522 .stdout(predicate::str::is_match(r"Wall Time\s+1\.234 s\s+±").unwrap());523524 hyperfine_debug()525 .arg("sleep 0.123")526 .assert()527 .success()518 .stdout(predicate::str::contains("Time (mean ± σ): 123.0 ms ±"));528 .stdout(predicate::str::is_match(r"Wall Time\s+123\.0 ms\s+±").unwrap());529530 hyperfine_debug()521 .arg("--time-unit=millisecond")531 .arg("--metrics=time_wall_clock:ms")532 .arg("sleep 1.234")533 .assert()534 .success()525 .stdout(predicate::str::contains("Time (mean ± σ): 1234.0 ms ±"));535 .stdout(predicate::str::is_match(r"Wall Time\s+1234\.0 ms\s+±").unwrap());536537 hyperfine_debug()528 .arg("--time-unit=microsecond")538 .arg("--metrics=time_wall_clock:us")539 .arg("sleep 1.234")540 .assert()541 .success()532 .stdout(predicate::str::contains(533 "Time (mean ± σ): 1234000.0 µs ±",534 ));542 .stdout(predicate::str::is_match(r"Wall Time\s+1234000\.0 µs\s+±").unwrap());543}544545#[test]546fn performs_ten_runs_for_slow_commands() {
85 unmodified lines
632 .stdout(predicate::str::contains("30 runs"));633}634635#[test]628fn shows_benchmark_comparison_with_relative_times() {636fn secondary_metrics_include_factors_for_large_changes() {637 // Mock CPU time is zero; secondary wall time still gets ratio annotations.638 let output = hyperfine_debug()639 .args([640 "--metrics=time_cpu,time_wall_clock",641 "--style=basic",642 "--runs=2",643 "sleep 1",644 "sleep 10",645 "sleep 0.1",646 ])647 .output()648 .unwrap();649 assert!(output.status.success(), "{:?}", output);650 let stdout = String::from_utf8(output.stdout).unwrap();651 assert!(stdout.contains("+900.0%"), "{}", stdout);652 assert!(stdout.contains("-90.0%"), "{}", stdout);653 assert!(stdout.contains("+900.0% (10.0x slower)"), "{}", stdout);654 assert!(stdout.contains("-90.0% (10.0x faster)"), "{}", stdout);655}656657#[test]658fn shows_multiple_metrics_relative_to_first_command() {659 let _settings = snapshot_settings().bind_to_scope();660 assert_cmd_snapshot!(hyperfine_debug()661 .arg("--style=basic")632 .arg("sleep 1.0")633 .arg("sleep 2.0")634 .arg("sleep 3.0"), @r"662 .arg("--metrics=time_wall_clock:ms,time_user:us,memory_peak_resident:MiB")663 .arg("sleep 0.0817")664 .arg("sleep 0.6155")665 .arg("sleep 0.1707"), @"666 success: true667 exit_code: 0668 ----- stdout -----638 Benchmark 1: sleep 1.0639 Time (mean ± σ): 1.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]640 Range (min … max): 1.000 s … 1.000 s 10 runs669 Benchmark 1: sleep 0.0817 (36 runs)670 mean ± σ min … max671 Wall Time 81.7 ms ± 0.0 ms 81.7 ms … 81.7 ms672 User time 0.0 µs ± 0.0 µs 0.0 µs … 0.0 µs673 Memory 0.0 MiB ± 0.0 MiB 0.0 MiB … 0.0 MiB674642 Benchmark 2: sleep 2.0643 Time (mean ± σ): 2.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]644 Range (min … max): 2.000 s … 2.000 s 10 runs675 Benchmark 2: sleep 0.6155 (10 runs)676 mean ± σ min … max677 Wall Time 615.5 ms ± 0.0 ms 615.5 ms … 615.5 ms +653.4% (7.5x slower)678 User time 0.0 µs ± 0.0 µs 0.0 µs … 0.0 µs N/A679 Memory 0.0 MiB ± 0.0 MiB 0.0 MiB … 0.0 MiB N/A680646 Benchmark 3: sleep 3.0647 Time (mean ± σ): 3.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]648 Range (min … max): 3.000 s … 3.000 s 10 runs681 Benchmark 3: sleep 0.1707 (17 runs)682 mean ± σ min … max683 Wall Time 170.7 ms ± 0.0 ms 170.7 ms … 170.7 ms +108.9% (2.1x slower)684 User time 0.0 µs ± 0.0 µs 0.0 µs … 0.0 µs N/A685 Memory 0.0 MiB ± 0.0 MiB 0.0 MiB … 0.0 MiB N/A686650 Summary651 sleep 1.0 ran652 2.00 ± 0.00 times faster than sleep 2.0653 3.00 ± 0.00 times faster than sleep 3.0687688 ----- stderr -----689 ");690}
1 unmodified line
692#[test]693fn shows_benchmark_comparison_with_same_time() {694 let _settings = snapshot_settings().bind_to_scope();695 assert_cmd_snapshot!(hyperfine_debug()696 .arg("--metrics=time_wall_clock,memory_peak_resident")697 .arg("--style=basic")698 .arg("--command-name=A")699 .arg("--command-name=B")700 .arg("sleep 1.0")701 .arg("sleep 1.0")702 .arg("sleep 2.0")669 .arg("sleep 1000.0"), @r"703 .arg("sleep 1000.0"), @"704 success: true705 exit_code: 0706 ----- stdout -----673 Benchmark 1: A674 Time (mean ± σ): 1.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]675 Range (min … max): 1.000 s … 1.000 s 10 runs707 Benchmark 1: A (10 runs)708 mean ± σ min … max709 Wall Time 1.000 s ± 0.000 s 1.000 s … 1.000 s710 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B711677 Benchmark 2: B678 Time (mean ± σ): 1.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]679 Range (min … max): 1.000 s … 1.000 s 10 runs712 Benchmark 2: B (10 runs)713 mean ± σ min … max714 Wall Time 1.000 s ± 0.000 s 1.000 s … 1.000 s 0.0%715 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B N/A716681 Benchmark 3: sleep 2.0682 Time (mean ± σ): 2.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]683 Range (min … max): 2.000 s … 2.000 s 10 runs717 Benchmark 3: sleep 2.0 (10 runs)718 mean ± σ min … max719 Wall Time 2.000 s ± 0.000 s 2.000 s … 2.000 s +100.0% (2.0x slower)720 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B N/A721685 Benchmark 4: sleep 1000.0686 Time (mean ± σ): 1000.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]687 Range (min … max): 1000.000 s … 1000.000 s 10 runs722 Benchmark 4: sleep 1000.0 (10 runs)723 mean ± σ min … max724 Wall Time 1000.000 s ± 0.000 s 1000.000 s … 1000.000 s +99900.0% (1000.0x slower)725 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B N/A726689 Summary690 A ran691 As fast (1.00 ± 0.00) as B692 2.00 ± 0.00 times faster than sleep 2.0693 1000.00 ± 0.00 times faster than sleep 1000.0727728 ----- stderr -----729 ");730}
1 unmodified line
732#[test]733fn shows_benchmark_comparison_relative_to_reference() {734 let _settings = snapshot_settings().bind_to_scope();735 assert_cmd_snapshot!(hyperfine_debug()736 .arg("--metrics=time_wall_clock,memory_peak_resident")737 .arg("--style=basic")704 .arg("--reference=sleep 2.0")738 .arg("sleep 2.0")739 .arg("sleep 1.0")706 .arg("sleep 3.0"), @r"740 .arg("sleep 3.0"), @"741 success: true742 exit_code: 0743 ----- stdout -----710 Benchmark 1: sleep 2.0711 Time (mean ± σ): 2.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]712 Range (min … max): 2.000 s … 2.000 s 10 runs744 Benchmark 1: sleep 2.0 (10 runs)745 mean ± σ min … max746 Wall Time 2.000 s ± 0.000 s 2.000 s … 2.000 s747 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B748714 Benchmark 2: sleep 1.0715 Time (mean ± σ): 1.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]716 Range (min … max): 1.000 s … 1.000 s 10 runs749 Benchmark 2: sleep 1.0 (10 runs)750 mean ± σ min … max751 Wall Time 1.000 s ± 0.000 s 1.000 s … 1.000 s -50.0% (2.0x faster)752 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B N/A753718 Benchmark 3: sleep 3.0719 Time (mean ± σ): 3.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]720 Range (min … max): 3.000 s … 3.000 s 10 runs754 Benchmark 3: sleep 3.0 (10 runs)755 mean ± σ min … max756 Wall Time 3.000 s ± 0.000 s 3.000 s … 3.000 s +50.0% (1.5x slower)757 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B N/A758722 Summary723 sleep 2.0 ran724 2.00 ± 0.00 times slower than sleep 1.0725 1.50 ± 0.00 times faster than sleep 3.0759760 ----- stderr -----761 ");762}763764#[test]732fn command_sorted_comparison_and_markup_identify_reference() {765fn comparison_and_markup_identify_first_command_as_reference() {766 let _settings = snapshot_settings().bind_to_scope();767 let directory = tempfile::tempdir().unwrap();768 let export_path = directory.path().join("results.md");769 let output = hyperfine_debug()770 .args([771 "--style=basic",772 "--runs=1",740 "--sort=command",741 "--reference",742 "sleep 2",743 "--reference-name",744 "baseline",773 "--command-name=baseline",774 "--export-markdown",775 ])776 .arg(&export_path)748 .args(["sleep 1", "sleep 2", "sleep 3"])777 .args(["sleep 2", "sleep 1", "sleep 2", "sleep 3"])778 .output()779 .unwrap();780 assert!(output.status.success(), "{:?}", output);781 let stdout = String::from_utf8(output.stdout).unwrap();753 let comparison = stdout.split_once("Relative speed comparison\n").unwrap().1;754 insta::assert_snapshot!(comparison, @r"755 1.00 baseline (reference)756 2.00 sleep 1 (faster)757 1.00 sleep 2 (same speed)758 1.50 sleep 3 (slower)759 ");782 assert!(783 stdout.contains("Benchmark 1: baseline (1 run)"),784 "{}",785 stdout786 );787 assert!(stdout.contains("-50.0%"), "{}", stdout);788 assert!(stdout.contains("0.0%"), "{}", stdout);789 assert!(stdout.contains("+50.0%"), "{}", stdout);790 let markdown = std::fs::read_to_string(export_path).unwrap();761 insta::assert_snapshot!(markdown, @r"762 | Command | Mean [s] | Min [s] | Max [s] | Relative |763 |:---|---:|---:|---:|---:|764 | `baseline` | 2.000 | 2.000 | 2.000 | 1.00 (reference) |765 | `sleep 1` | 1.000 | 1.000 | 1.000 | 2.00 (faster) |766 | `sleep 2` | 2.000 | 2.000 | 2.000 | 1.00 (same speed) |767 | `sleep 3` | 3.000 | 3.000 | 3.000 | 1.50 (slower) |791 insta::assert_snapshot!(markdown, @"792 | Command | Mean Wall Time [s] | Change | Factor |793 |:---|---:|---:|:---|794 | `baseline` | 2.000 | | |795 | `sleep 1` | 1.000 | -50.0% | (2.0x faster) |796 | `sleep 2` | 2.000 | 0.0% | |797 | `sleep 3` | 3.000 | +50.0% | (1.5x slower) |798 ");799800 // Equal zero times have no meaningful relative factor.801 let output = hyperfine_debug()802 .args([803 "--style=none",804 "--runs=1",805 "--export-markdown=-",776 "--reference",806 "--command-name=baseline",807 "sleep 0",778 "--reference-name",779 "baseline",808 "sleep 0",809 ])810 .output()811 .unwrap();
2 unmodified lines
814 let row = markdown815 .lines()816 .find(|line| line.contains("sleep 0"))817 .unwrap();790 assert!(row.ends_with("| N/A |"), "{}", row);818 assert!(row.ends_with("| N/A | |"), "{}", row);819}820821#[test]794fn shows_reference_name() {795 let _settings = snapshot_settings().bind_to_scope();796 assert_cmd_snapshot!(hyperfine_debug()797 .arg("--style=basic")798 .arg("--reference=sleep 2.0")799 .arg("--reference-name=refabc123")800 .arg("sleep 1.0")801 .arg("sleep 3.0"), @r"802 success: true803 exit_code: 0804 ----- stdout -----805 Benchmark 1: refabc123806 Time (mean ± σ): 2.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]807 Range (min … max): 2.000 s … 2.000 s 10 runs808809 Benchmark 2: sleep 1.0810 Time (mean ± σ): 1.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]811 Range (min … max): 1.000 s … 1.000 s 10 runs812813 Benchmark 3: sleep 3.0814 Time (mean ± σ): 3.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]815 Range (min … max): 3.000 s … 3.000 s 10 runs816817 Summary818 refabc123 ran819 2.00 ± 0.00 times slower than sleep 1.0820 1.50 ± 0.00 times faster than sleep 3.0821822 ----- stderr -----823 ");824}825826#[test]822fn performs_all_benchmarks_in_parameter_scan() {823 let _settings = snapshot_settings().bind_to_scope();824 assert_cmd_snapshot!(hyperfine_debug()825 .arg("--metrics=time_wall_clock,memory_peak_resident")826 .arg("--style=basic")827 .arg("--parameter-scan")828 .arg("time")829 .arg("30")830 .arg("45")831 .arg("--parameter-step-size")832 .arg("5")837 .arg("sleep {time}"), @r"833 .arg("sleep {time}"), @"834 success: true835 exit_code: 0836 ----- stdout -----841 Benchmark 1: sleep 30842 Time (mean ± σ): 30.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]843 Range (min … max): 30.000 s … 30.000 s 10 runs837 Benchmark 1: sleep 30 (10 runs)838 mean ± σ min … max839 Wall Time 30.000 s ± 0.000 s 30.000 s … 30.000 s840 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B841845 Benchmark 2: sleep 35846 Time (mean ± σ): 35.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]847 Range (min … max): 35.000 s … 35.000 s 10 runs842 Benchmark 2: sleep 35 (10 runs)843 mean ± σ min … max844 Wall Time 35.000 s ± 0.000 s 35.000 s … 35.000 s +16.7%845 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B N/A846849 Benchmark 3: sleep 40850 Time (mean ± σ): 40.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]851 Range (min … max): 40.000 s … 40.000 s 10 runs847 Benchmark 3: sleep 40 (10 runs)848 mean ± σ min … max849 Wall Time 40.000 s ± 0.000 s 40.000 s … 40.000 s +33.3% (1.3x slower)850 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B N/A851853 Benchmark 4: sleep 45854 Time (mean ± σ): 45.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]855 Range (min … max): 45.000 s … 45.000 s 10 runs852 Benchmark 4: sleep 45 (10 runs)853 mean ± σ min … max854 Wall Time 45.000 s ± 0.000 s 45.000 s … 45.000 s +50.0% (1.5x slower)855 Memory 0.0 B ± 0.0 B 0.0 B … 0.0 B N/A856857 Summary858 sleep 30 ran859 1.17 ± 0.00 times faster than sleep 35860 1.33 ± 0.00 times faster than sleep 40861 1.50 ± 0.00 times faster than sleep 45857858 ----- stderr -----859 ");860}
15 unmodified lines
876}877878#[cfg(unix)]879#[test]885fn selects_reference_with_parameterized_prepare() {880fn preserves_input_order_with_parameterized_prepare() {881 let directory = tempfile::tempdir().unwrap();882 let csv_path = directory.path().join("results.csv");883 let json_path = directory.path().join("results.json");884 let output = hyperfine_raw_command()
5 unmodified lines
890 "delay",891 "0.2,0.4,0.6",892 "--prepare",893 "sleep {delay}",899 "--reference",900 "echo a (delay = 0.4)",894 "--export-csv",895 ])896 .arg(&csv_path)897 .arg("--export-json")
6 unmodified lines
904 assert_eq!(stdout.matches("Benchmark ").count(), 3);905 for (number, delay) in ["0.2", "0.4", "0.6"].iter().enumerate() {906 assert!(907 stdout.contains(&format!(915 "Benchmark {}: echo a (delay = {})",908 "Benchmark {}: echo a (delay = {}) (1 run)",909 number + 1,910 delay911 )),912 "{}",913 stdout914 );915 }923 assert!(stdout.contains("echo a (delay = 0.4) ran"), "{}", stdout);916 assert!(917 !stdout918 .split("Benchmark 2")919 .next()920 .unwrap()921 .contains("Change"),922 "{}",923 stdout924 );925 assert!(!stdout.contains("Change vs #1"));926927 let mut csv = csv::Reader::from_path(csv_path).unwrap();928 assert!(csv929 .headers()
17 unmodified lines
947 );948}949950#[test]949fn rejects_unmatched_reference_before_export_or_setup() {951fn rejects_invalid_metric_before_export_or_setup() {952 let directory = tempfile::tempdir().unwrap();953 let export_path = directory.path().join("results.csv");954 let marker_path = directory.path().join("setup-ran");955 std::fs::write(&export_path, "previous contents").unwrap();956957 hyperfine()956 .args(["--reference", "sleep 1", "-P", "secs", "2", "3", "--setup"])958 .args([959 "--metrics=memory_peak_resident:ms",960 "-P",961 "secs",962 "2",963 "3",964 "--setup",965 ])966 .arg(format!("echo touched > \"{}\"", marker_path.display()))967 .arg("--export-csv")968 .arg(&export_path)969 .arg("sleep {secs}")970 .assert()971 .failure()972 .stdout(predicate::str::is_empty())973 .stderr(predicate::str::contains(965 "does not match any parameterized benchmark",974 "Unit 'ms' is not valid for metric 'memory_peak_resident'",975 ));976 assert_eq!(977 std::fs::read_to_string(export_path).unwrap(),978 "previous contents"979 );980 assert!(!marker_path.exists());981}982974#[test]975fn rejects_ambiguous_parameterized_reference() {976 hyperfine_debug()977 .args([978 "-L",979 "x",980 "1,2",981 "--command-name",982 "case",983 "--reference",984 "case",985 "sleep {x}",986 ])987 .assert()988 .failure()989 .stderr(predicate::str::contains(990 "matches multiple parameterized benchmarks",991 ));992}993983#[cfg(unix)]984#[test]996fn intermediate_markdown_waits_for_selected_reference() {985fn intermediate_markdown_retains_completed_reference() {986 let directory = tempfile::tempdir().unwrap();987 let export_path = directory.path().join("results.md");988 hyperfine()989 .args([
2 unmodified lines
992 "--runs=1",993 "-L",994 "delay",995 "0.01,0.02,0.03",1007 "--reference",1008 "sleep 0.02",996 "--prepare",997 "true",998 "--prepare",999 "false",
9 unmodified lines
1009 let row = markdown1010 .lines()1011 .find(|line| line.contains("sleep 0.01"))1012 .unwrap();1026 assert!(row.ends_with("| N/A |"), "{}", row);1013 assert!(row.ends_with("| | |"), "{}", row);1014}10151016#[test]1030fn markdown_export_uses_selected_parameterized_reference() {1017fn markdown_export_uses_first_parameterized_benchmark_as_reference() {1018 let _settings = snapshot_settings().bind_to_scope();1019 assert_cmd_snapshot!(hyperfine_debug()1020 .args([1021 "--style=none",
4 unmodified lines
1026 "1",1027 "3",1028 "--command-name",1029 "case-{x}",1043 "--reference",1044 "case-2",1030 "sleep {x}",1046 ]), @r"1031 ]), @"1032 success: true1033 exit_code: 01034 ----- stdout -----10351051 | Command | Mean [s] | Min [s] | Max [s] | Relative |1052 |:---|---:|---:|---:|---:|1053 | `case-1` | 1.000 | 1.000 | 1.000 | 2.00 (faster) |1054 | `case-2` | 2.000 | 2.000 | 2.000 | 1.00 (reference) |1055 | `case-3` | 3.000 | 3.000 | 3.000 | 1.50 (slower) |1036 | Command | Mean Wall Time [s] | Change | Factor |1037 |:---|---:|---:|:---|1038 | `case-1` | 1.000 | | |1039 | `case-2` | 2.000 | +100.0% | (2.0x slower) |1040 | `case-3` | 3.000 | +200.0% | (3.0x slower) |104110421043 ----- stderr -----1044 ");
6 unmodified lines
1051 .arg("--style=none") // To only see the Markdown export on stdout1052 .arg("--export-markdown")1053 .arg("-")1054 .arg("sleep 1")1070 .arg("sleep 2"), @r"1055 .arg("sleep 2"), @"1056 success: true1057 exit_code: 01058 ----- stdout -----10591075 | Command | Mean [s] | Min [s] | Max [s] | Relative |1076 |:---|---:|---:|---:|---:|1077 | `sleep 1` | 1.000 ± 0.000 | 1.000 | 1.000 | 1.00 |1078 | `sleep 2` | 2.000 ± 0.000 | 2.000 | 2.000 | 2.00 ± 0.00 |1060 | Command | Mean Wall Time [s] | Change | Factor |1061 |:---|---:|---:|:---|1062 | `sleep 1` | 1.000 ± 0.000 | | |1063 | `sleep 2` | 2.000 ± 0.000 | +100.0% | (2.0x slower) |106410651066 ----- stderr -----1067 ");
74 unmodified lines
1142 success: true1143 exit_code: 01144 ----- stdout -----11451161 | Command | Mean [s] | Min [s] | Max [s] | Relative |1162 |:---|---:|---:|---:|---:|1163 | `` echo `uname` \| cat `` | 1.000 ± 0.000 | 1.000 | 1.000 | 1.00 |1146 | Command | Mean Wall Time [s] | Change | Factor |1147 |:---|---:|---:|:---|1148 | `` echo `uname` \| cat `` | 1.000 ± 0.000 | | |114911501151 ----- stderr -----1152 ");
14 unmodified lines
1167 .and(predicate::str::contains("echo test (branch = feature)")),1168 );1169}11701186#[test]1187fn speed_comparison_sort_order() {1188 let _settings = snapshot_settings().bind_to_scope();1189 insta::allow_duplicates! {1190 for sort_order in ["auto", "mean-time"] {1191 assert_cmd_snapshot!(hyperfine_debug()1192 .arg("--style=basic")1193 .arg("sleep 2")1194 .arg("sleep 1")1195 .arg(format!("--sort={sort_order}")), @r"1196 success: true1197 exit_code: 01198 ----- stdout -----1199 Benchmark 1: sleep 21200 Time (mean ± σ): 2.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]1201 Range (min … max): 2.000 s … 2.000 s 10 runs12021203 Benchmark 2: sleep 11204 Time (mean ± σ): 1.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]1205 Range (min … max): 1.000 s … 1.000 s 10 runs12061207 Summary1208 sleep 1 ran1209 2.00 ± 0.00 times faster than sleep 212101211 ----- stderr -----1212 ");1213 }1214 }12151216 assert_cmd_snapshot!(hyperfine_debug()1217 .arg("--style=basic")1218 .arg("sleep 2")1219 .arg("sleep 1")1220 .arg("--sort=command"), @r"1221 success: true1222 exit_code: 01223 ----- stdout -----1224 Benchmark 1: sleep 21225 Time (mean ± σ): 2.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]1226 Range (min … max): 2.000 s … 2.000 s 10 runs12271228 Benchmark 2: sleep 11229 Time (mean ± σ): 1.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]1230 Range (min … max): 1.000 s … 1.000 s 10 runs12311232 Relative speed comparison1233 2.00 ± 0.00 sleep 21234 1.00 sleep 112351236 ----- stderr -----1237 ");1238}12391171#[cfg(windows)]1172#[test]1173fn windows_quote_args() {1174 hyperfine()
63 unmodified lines
1238 "--style=none",1239 "--export-json=-",1240 "--runs=2",1241 "--warmup=1",1311 "--reference-name=one second",1312 "--reference=sleep 1",1242 "--command-name=one second",1243 "sleep 1",1244 "--command-name=sleep 2",1245 "sleep 2",1246 ]));1247}
20 unmodified lines
1268 "-L",1269 "duration",1270 "1,2",1271 "--command-name=sleep for {duration} seconds",1341 "--reference=sleep for 2 seconds",1272 "sleep {duration}",1273 ]));1274}
modified:CHANGELOG.md+10 added
1# Unreleased23## Features45- Add support for alternative performance metrics (peak memory usage, CPU cycles, instructions, cache misses, branch misses, ...). By default, hyperfine will now display wall-clock time and peak memory usage,6 but users can use the new `--metrics` option to select different performance metrics.7- The terminal output now shows an overview of all measured performance metrics, including relative changes.89## Breaking changes1011- Benchmarked commands are now always executed directly, without an intermediate shell (`--shell=none`). Use `-S` (an alias for `--shell=default`) to restore the previous behavior (`sh` on Unix, `cmd.exe` on Windows), or select a shell with `--shell <SHELL>`.12- The JSON format for `--export-json` has changed (schema version 2). The new format now includes metadata, per-run measurements, and statistical summaries for all measured quantities, see #790 (@sharkdp). Code that reads those exported JSON files must be updated. For example, `results[i].mean` is now `results[i].summary.time_wall_clock.mean`, and `results[i].times` is replaced by `results[i].measurements[j].time_wall_clock.value`. The new structure looks like this:
38 unmodified lines
51 }52 ```5354 Times are always exported in seconds and memory in bytes.55- `--time-unit`/`-u` has been removed. Units can now be selected using the `--metrics METRIC[:UNIT],…` option, e.g. `--metrics time_wall_clock:ms,memory_peak_resident:MiB`.56- `--sort` has been removed. It complicated hyperfine significantly and doesn't make too much sense with the new output format.57- `--reference` and `--reference-name` have been removed (for now). The first command is always considered as the reference command.58- The format of Markdown, AsciiDoc, org-mode and CSV exports has also been changed. CSV now includes columns with the name and the unit of the primary metric.5960# v1.21.06162## Features
453 unmodified lines
modified:README.md+61 added-24 removed
14 unmodified lines
15* Statistical analysis across multiple runs.16* Support for arbitrary shell commands.17* Constant feedback about the benchmark progress and current estimates.18* Warmup runs can be executed before the actual benchmark.19* Cache-clearing commands can be set up before each timing run.19* Cache-clearing commands can be set up before each benchmark run.20* Statistical outlier detection to detect interference from other programs and caching effects.21* Export results to various formats: CSV, JSON, Markdown, AsciiDoc.22* Parameterized benchmarks (e.g. vary the number of threads).23* Cross-platform
16 unmodified lines
40```sh41hyperfine --runs 5 'sleep 0.3'42```4344If you want to compare the runtimes of different programs, you can pass multiple commands:44If you want to compare different programs, you can pass multiple commands:45```sh46hyperfine 'hexdump file' 'xxd file'47```4849Commands run and appear in input order. The first command is the reference for all comparisons;50each subsequent result shows its change from that reference.5152### Warmup runs and preparation commands5354For programs that perform a lot of disk I/O, the benchmarking results can be heavily influenced55by disk caches and whether they are cold or warm.
4 unmodified lines
60hyperfine -S --warmup 3 'grep -R TODO *'61```6263Conversely, if you want to run the benchmark for a cold cache, you can use the `-p`/`--prepare`61option to run a special command before *each* timing run. For example, to clear Linux filesystem caches,64option to run a special command before *each* benchmark run. For example, to clear Linux filesystem caches,65you can run66```sh67sync; echo 3 | sudo tee /proc/sys/vm/drop_caches68```
23 unmodified lines
92hyperfine -L compiler g++,clang++ '{compiler} -O2 main.cpp'93```9495A common use case is comparing the same command across multiple Git branches. Use `--setup`93to switch branches once before each set of timing runs, so the branch switch is not part of96to switch branches once before each set of benchmark runs, so the branch switch is not part of97the measured command:98```sh99hyperfine \100 --parameter-list branch main,performance-improvements \
30 unmodified lines
131If any of these commands need shell syntax, enable a shell explicitly.132133When a shell is enabled, hyperfine *corrects for the shell spawning time*. It runs the shell with an134empty command multiple times to measure its startup time, then subtracts this time from each132measurement.135time measurement.136137138### Shell functions139
10 unmodified lines
150```sh151hyperfine -S 'my_function() { sleep 1; }; my_function'152```153151### Exporting results154### Choosing metrics and units155153Hyperfine has multiple options for exporting benchmark results to CSV, JSON, Markdown and other154formats (see `--help` text for details).156By default, hyperfine displays wall-clock time and memory usage157(`time_wall_clock,memory_peak_resident`). Use `--metrics` with a158comma-separated list to select a different set of metrics. Each159metric can have an optional unit after it:160156#### Markdown161```sh162hyperfine \163 --metrics memory_peak_resident:MiB,time_wall_clock:ms,instructions \164 './baseline' './candidate'165```166158You can use the `--export-markdown <file>` option to create tables like the following:167The following metrics are available:168160| Command | Mean [s] | Min [s] | Max [s] | Relative |161|:---|---:|---:|---:|---:|162| `find . -iregex '.*[0-9]\.jpg$'` | 2.275 ± 0.046 | 2.243 | 2.397 | 9.79 ± 0.22 |163| `find . -iname '*[0-9].jpg'` | 1.427 ± 0.026 | 1.405 | 1.468 | 6.14 ± 0.13 |164| `fd -HI '.*[0-9]\.jpg$'` | 0.232 ± 0.002 | 0.230 | 0.236 | 1.00 |165166#### JSON167168The JSON export includes the following metrics for each measured run (excluding warmup runs):169169- **`time_wall_clock`**: Time from start to finish, including time spent waiting, in seconds.170172- **`time_user`**: CPU time spent running the program's code, summed across threads, in seconds.171- **`time_user`**: CPU time spent executing application and library code in user mode,172 summed across threads, in seconds.173174 - Linux/macOS: Includes child-process time when parents wait for their children to finish.175 - Windows: Includes the command and its child processes.176177- **`time_system`**: CPU time spent running operating-system code for the program, for example177- **`time_system`**: CPU time spent executing kernel code on the program's behalf, for example178 to read files, summed across threads, in seconds.179180 - Linux/macOS: Includes child-process time when parents wait for their children to finish.181 - Windows: Includes the command and its child processes.182183- **`time_cpu`**: Total CPU time, calculated as `time_user + time_system` for each run, in seconds.184 It excludes time spent sleeping or waiting without executing. CPU time is summed across185 threads, so it can exceed wall-clock time: four threads running on four cores for one second186 can consume roughly four CPU-seconds.187188- **`memory_peak_resident`**: Peak memory held in physical RAM, in bytes.189190 - Linux/macOS: Peak resident set size (RSS). This is the largest per-process peak among the191 command and child processes (whose usage is collected when their parents wait for them),
27 unmodified lines
219220 - Linux: Same scope as `cpu_cycles`.221 - macOS/Windows: Currently not supported.222218Hardware counters are not available if a `--shell` is used.223Note that hardware counters are not available if a `--shell` is used.224225Time measurements support units `ns`, `us`, `ms`, `s`, `min`, and `h`. Memory measurements226support `B`, `kB`, `MB`, `GB`, `TB`, `KiB`, `MiB`, `GiB`, and `TiB`. Hardware counters227support `count` (1), `k` (thousand), `M` (million), and `B` (billion).228229You can also use a preset to select a group of metrics:230231| Preset | Metrics |232|:---|:---|233| `--metrics=default` | `time_wall_clock,memory_peak_resident` |234| `--metrics=time` | `time_wall_clock,time_cpu,time_user,time_system` |235| `--metrics=all` | All available metrics |236237### Exporting results238239Hyperfine can export results to CSV, JSON, Markdown, AsciiDoc, and org-mode. Non-JSON formats240contain only the primary metric.241242#### Markdown243244You can use the `--export-markdown <file>` option to create tables like the following:245246| Command | Mean Wall Time [s] | Change | Factor |247|:---|---:|---:|:---|248| `find . -iregex '.*[0-9]\.jpg$'` | 2.275 ± 0.046 | | |249| `find . -iname '*[0-9].jpg'` | 1.427 ± 0.026 | -37.3% | (1.6x faster) |250| `fd -HI '.*[0-9]\.jpg$'` | 0.232 ± 0.002 | -89.8% | (9.8x faster) |251252#### JSON253254The JSON export includes all available metrics listed in [Choosing metrics and units](#choosing-metrics-and-units)255for each measured run (excluding warmup runs).256257The JSON output is useful if you want to analyze the benchmark results in more detail. The258[`scripts/`](https://github.com/sharkdp/hyperfine/tree/master/scripts) folder includes a lot259of helpful Python programs to further analyze benchmark results and create helpful260visualizations, like a histogram of runtimes or a whisker plot to compare
4 unmodified lines
265266267### Detailed benchmark flowchart268232The following chart explains the execution order of various timing runs when using options269The following chart explains the execution order of various benchmark runs when using options270like `--warmup`, `--prepare <cmd>`, `--setup <cmd>` or `--cleanup <cmd>`:271272![](doc/execution-order.png)273
177 unmodified lines