Compare commits

...
Author SHA1 Message Date
David Peter 27c98c6f87 Make plotting scripts runnable with uv 2026-10-07 11:24:14 +02:00
10 changed files with 301 additions and 209 deletions

No files matched your search

+10 -1
View File
@@ -257,7 +257,16 @@ The JSON output is useful if you want to analyze the benchmark results in more d
[`scripts/`](https://github.com/sharkdp/hyperfine/tree/master/scripts) folder includes a lot [`scripts/`](https://github.com/sharkdp/hyperfine/tree/master/scripts) folder includes a lot
of helpful Python programs to further analyze benchmark results and create helpful of helpful Python programs to further analyze benchmark results and create helpful
visualizations, like a histogram of runtimes or a whisker plot to compare visualizations, like a histogram of runtimes or a whisker plot to compare
multiple benchmarks: multiple benchmarks.
For example, these two commands create the following plots:
```bash
uvx --from 'git+https://github.com/sharkdp/hyperfine' \
plot_histogram results.json
uvx --from 'git+https://github.com/sharkdp/hyperfine' \
plot_whisker results.json
```
| ![](doc/histogram.png) | ![](doc/whisker.png) | | ![](doc/histogram.png) | ![](doc/whisker.png) |
|---:|---:| |---:|---:|
+36
View File
@@ -0,0 +1,36 @@
[project]
name = "hyperfine-scripts"
version = "0.1.0"
description = "Plot and analyze hyperfine JSON benchmark results"
requires-python = ">=3.10"
license-files = ["LICENSE-APACHE", "LICENSE-MIT"]
dependencies = [
"matplotlib",
"numpy",
"pyqt6",
"scipy",
]
[project.scripts]
advanced_statistics = "advanced_statistics:main"
plot_benchmark_comparison = "plot_benchmark_comparison:main"
plot_histogram = "plot_histogram:main"
plot_parametrized = "plot_parametrized:main"
plot_progression = "plot_progression:main"
plot_whisker = "plot_whisker:main"
welch_ttest = "welch_ttest:main"
[tool.uv.build-backend]
module-root = "scripts"
module-name = ""
namespace = true
source-exclude = [
"/scripts/README.md",
"/scripts/ruff.toml",
"/scripts/.*",
"*.egg-info",
]
[build-system]
requires = ["uv_build>=0.12.23,<0.13"]
build-backend = "uv_build"
+23 -13
View File
@@ -1,23 +1,33 @@
This folder contains scripts that can be used in combination with hyperfine's `--export-json` option. This folder contains scripts that can be used in combination with hyperfine's `--export-json` option.
### Example: ### Run directly from GitHub
Install [`uv`](https://docs.astral.sh/uv/getting-started/installation/), then
run one of the scripts:
```bash ```bash
hyperfine 'sleep 0.020' 'sleep 0.021' 'sleep 0.022' --export-json sleep.json hyperfine 'sleep 0.020' 'sleep 0.021' 'sleep 0.022' --export-json sleep.json
uv run plot_whisker.py sleep.json uvx --from 'git+https://github.com/sharkdp/hyperfine' \
plot_whisker sleep.json
``` ```
All plotting and analysis scripts use the JSON export's `primary_metric` by default. Replace `plot_whisker` with any of the following commands.
| Command | Description |
| --- | --- |
| `plot_whisker` | Compare benchmarks with a box and whisker plot |
| `plot_histogram` | Show the distribution of measurements |
| `plot_parametrized` | Plot results from a parameter scan |
| `plot_progression` | Show measurements in run order |
| `plot_benchmark_comparison` | Compare commands across multiple JSON exports |
| `advanced_statistics` | Print additional statistics and percentiles |
| `welch_ttest` | Compare two benchmarks using Welch's t-test |
By default, the plotting and analysis scripts use the metric that was selected
first in the actual hyperfine run (`--metrics` option).
Use `--metric` to select another metric:
```bash ```bash
uv run plot_histogram.py benchmark.json --metric instructions uvx --from 'git+https://github.com/sharkdp/hyperfine' \
plot_histogram benchmark.json --metric instructions
``` ```
### Prerequisites
Install [`uv`](https://docs.astral.sh/uv/getting-started/installation/) and run the
commands above from this directory.
The scripts declare their dependencies using [PEP 723](https://peps.python.org/pep-0723/)
inline script metadata. `uv run` automatically installs these dependencies in an
isolated environment before running the script.
+19 -15
View File
@@ -12,33 +12,33 @@ import numpy as np
from plot_utils import METRICS, add_metric_argument, load_results from plot_utils import METRICS, add_metric_argument, load_results
parser = argparse.ArgumentParser()
parser.add_argument("file", help="JSON file with benchmark results") def main():
add_metric_argument(parser) parser = argparse.ArgumentParser()
parser.add_argument( parser.add_argument("file", help="JSON file with benchmark results")
add_metric_argument(parser)
parser.add_argument(
"--time-unit", "--time-unit",
help="Display unit for time metrics (default: second).", help="Display unit for time metrics (default: second).",
choices=["second", "millisecond"], choices=["second", "millisecond"],
) )
args = parser.parse_args() args = parser.parse_args()
metric, [results] = load_results(parser, [args.file], args.metric) metric, [results] = load_results(parser, [args.file], args.metric)
description = METRICS[metric] description = METRICS[metric]
unit, scale = description.unit, description.scale unit, scale = description.unit, description.scale
if args.time_unit is not None: if args.time_unit is not None:
if not metric.startswith("time_"): if not metric.startswith("time_"):
parser.error("--time-unit can only be used with a time metric") parser.error("--time-unit can only be used with a time metric")
if args.time_unit == "millisecond": if args.time_unit == "millisecond":
unit, scale = "ms", 0.001 unit, scale = "ms", 0.001
def format_value(value):
def format_value(value):
suffix = f" {unit}" if unit else "" suffix = f" {unit}" if unit else ""
return f"{value:.3f}{suffix}" return f"{value:.3f}{suffix}"
print(f"Metric: {description.label}\n")
print(f"Metric: {description.label}\n") for result in results:
for result in results:
summary = result["summary"][metric] summary = result["summary"][metric]
values = [m[metric]["value"] / scale for m in result["measurements"]] values = [m[metric]["value"] / scale for m in result["measurements"]]
@@ -60,3 +60,7 @@ for result in results:
f" (IQR = {format_value(iqr)})" f" (IQR = {format_value(iqr)})"
) )
print() print()
if __name__ == "__main__":
main()
+38 -32
View File
@@ -21,31 +21,33 @@ import numpy as np
from plot_utils import METRICS, add_metric_argument, load_results from plot_utils import METRICS, add_metric_argument, load_results
parser = argparse.ArgumentParser(description=__doc__)
add_metric_argument(parser) def main():
parser.add_argument( parser = argparse.ArgumentParser(description=__doc__)
add_metric_argument(parser)
parser.add_argument(
"files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results" "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"
) )
parser.add_argument("--title", help="Plot Title") parser.add_argument("--title", help="Plot Title")
parser.add_argument( parser.add_argument(
"--benchmark-names", nargs="+", help="Names of the benchmark groups" "--benchmark-names", nargs="+", help="Names of the benchmark groups"
) )
parser.add_argument("-o", "--output", help="Save image to the given filename") parser.add_argument("-o", "--output", help="Save image to the given filename")
args = parser.parse_args() args = parser.parse_args()
metric, datasets = load_results(parser, args.files, args.metric) metric, datasets = load_results(parser, args.files, args.metric)
metric_info = METRICS[metric] metric_info = METRICS[metric]
commands = None commands = None
data = [] data = []
inputs = [] inputs = []
if args.benchmark_names: if args.benchmark_names:
assert len(args.files) == len(args.benchmark_names), ( assert len(args.files) == len(args.benchmark_names), (
"Number of benchmark names must match the number of input files." "Number of benchmark names must match the number of input files."
) )
for i, (filename, results) in enumerate(zip(args.files, datasets)): for i, (filename, results) in enumerate(zip(args.files, datasets)):
benchmark_commands = [b.get("name", b["command"]) for b in results] benchmark_commands = [b.get("name", b["command"]) for b in results]
if commands is None: if commands is None:
commands = benchmark_commands commands = benchmark_commands
@@ -59,27 +61,31 @@ for i, (filename, results) in enumerate(zip(args.files, datasets)):
else: else:
inputs.append(filename.stem) inputs.append(filename.stem)
data = np.transpose(data) data = np.transpose(data)
x = np.arange(len(inputs)) # the label locations x = np.arange(len(inputs)) # the label locations
width = 0.25 # the width of the bars width = 0.25 # the width of the bars
fig, ax = plt.subplots(layout="constrained") fig, ax = plt.subplots(layout="constrained")
fig.set_figheight(5) fig.set_figheight(5)
fig.set_figwidth(10) fig.set_figwidth(10)
for i, command in enumerate(commands): for i, command in enumerate(commands):
offset = width * (i + 1) offset = width * (i + 1)
rects = ax.bar(x + offset, data[i], width, label=command) ax.bar(x + offset, data[i], width, label=command)
ax.set_xticks(x + 0.5, inputs) ax.set_xticks(x + 0.5, inputs)
ax.grid(visible=True, axis="y") ax.grid(visible=True, axis="y")
if args.title: if args.title:
plt.title(args.title) plt.title(args.title)
plt.xlabel("Benchmark") plt.xlabel("Benchmark")
plt.ylabel(metric_info.axis_label) plt.ylabel(metric_info.axis_label)
plt.legend(title="Command") plt.legend(title="Command")
if args.output: if args.output:
plt.savefig(args.output) plt.savefig(args.output)
else: else:
plt.show() plt.show()
if __name__ == "__main__":
main()
+50 -43
View File
@@ -17,15 +17,17 @@ import numpy as np
from plot_utils import METRICS, add_metric_argument, load_results from plot_utils import METRICS, add_metric_argument, load_results
parser = argparse.ArgumentParser(description=__doc__)
add_metric_argument(parser) def main():
parser.add_argument("file", help="JSON file with benchmark results") parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--title", help="Plot title") add_metric_argument(parser)
parser.add_argument( parser.add_argument("file", help="JSON file with benchmark results")
parser.add_argument("--title", help="Plot title")
parser.add_argument(
"--labels", help="Comma-separated list of entries for the plot legend" "--labels", help="Comma-separated list of entries for the plot legend"
) )
parser.add_argument("--bins", help="Number of bins (default: auto)") parser.add_argument("--bins", help="Number of bins (default: auto)")
parser.add_argument( parser.add_argument(
"--legend-location", "--legend-location",
help="Location of the legend on plot (default: upper center)", help="Location of the legend on plot (default: upper center)",
choices=[ choices=[
@@ -43,82 +45,87 @@ parser.add_argument(
"center", "center",
], ],
default="upper center", default="upper center",
) )
parser.add_argument( parser.add_argument(
"--type", help="Type of histogram (*bar*, barstacked, step, stepfilled)" "--type", help="Type of histogram (*bar*, barstacked, step, stepfilled)"
) )
parser.add_argument("-o", "--output", help="Save image to the given filename.") parser.add_argument("-o", "--output", help="Save image to the given filename.")
parser.add_argument( parser.add_argument(
"--min", "--min",
"--t-min", "--t-min",
dest="value_min", dest="value_min",
type=float, type=float,
help="Minimum metric value to display", help="Minimum metric value to display",
) )
parser.add_argument( parser.add_argument(
"--max", "--max",
"--t-max", "--t-max",
dest="value_max", dest="value_max",
type=float, type=float,
help="Maximum metric value to display", help="Maximum metric value to display",
) )
parser.add_argument( parser.add_argument(
"--log-count", "--log-count",
help="Use a logarithmic y-axis for the event count", help="Use a logarithmic y-axis for the event count",
action="store_true", action="store_true",
) )
args = parser.parse_args() args = parser.parse_args()
metric, [results] = load_results(parser, [args.file], args.metric) metric, [results] = load_results(parser, [args.file], args.metric)
metric_info = METRICS[metric] metric_info = METRICS[metric]
if args.labels: if args.labels:
labels = args.labels.split(",") labels = args.labels.split(",")
else: else:
labels = [b.get("name", b["command"]) for b in results] labels = [b.get("name", b["command"]) for b in results]
all_values = [ all_values = [
[m[metric]["value"] / metric_info.scale for m in b["measurements"]] for b in results [m[metric]["value"] / metric_info.scale for m in b["measurements"]]
] for b in results
]
value_min = ( value_min = (
args.value_min args.value_min
if args.value_min is not None if args.value_min is not None
else np.min(list(map(np.min, all_values))) else np.min(list(map(np.min, all_values)))
) )
value_max = ( value_max = (
args.value_max args.value_max
if args.value_max is not None if args.value_max is not None
else np.max(list(map(np.max, all_values))) else np.max(list(map(np.max, all_values)))
) )
bins = int(args.bins) if args.bins else "auto" bins = int(args.bins) if args.bins else "auto"
histtype = args.type if args.type else "bar" histtype = args.type if args.type else "bar"
plt.figure(figsize=(10, 5)) plt.figure(figsize=(10, 5))
plt.hist( plt.hist(
all_values, all_values,
label=labels, label=labels,
bins=bins, bins=bins,
histtype=histtype, histtype=histtype,
range=(value_min, value_max), range=(value_min, value_max),
) )
plt.legend( plt.legend(
loc=args.legend_location, loc=args.legend_location,
fancybox=True, fancybox=True,
shadow=True, shadow=True,
prop={"size": 10, "family": ["Source Code Pro", "Fira Mono", "Courier New"]}, prop={"size": 10, "family": ["Source Code Pro", "Fira Mono", "Courier New"]},
) )
plt.xlabel(metric_info.axis_label) plt.xlabel(metric_info.axis_label)
if args.title: if args.title:
plt.title(args.title) plt.title(args.title)
if args.log_count: if args.log_count:
plt.yscale("log") plt.yscale("log")
else: else:
plt.ylim(0, None) plt.ylim(0, None)
if args.output: if args.output:
plt.savefig(args.output, dpi=600) plt.savefig(args.output, dpi=600)
else: else:
plt.show() plt.show()
if __name__ == "__main__":
main()
+35 -33
View File
@@ -17,46 +17,46 @@ import matplotlib.pyplot as plt
from plot_utils import METRICS, add_metric_argument, load_results from plot_utils import METRICS, add_metric_argument, load_results
parser = argparse.ArgumentParser(description=__doc__)
add_metric_argument(parser) def main():
parser.add_argument("file", help="JSON file with benchmark results", nargs="+") parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument( add_metric_argument(parser)
parser.add_argument("file", help="JSON file with benchmark results", nargs="+")
parser.add_argument(
"--parameter-name", "--parameter-name",
metavar="name", metavar="name",
type=str, type=str,
help="Deprecated; parameter names are now inferred from benchmark files", help="Deprecated; parameter names are now inferred from benchmark files",
) )
parser.add_argument( parser.add_argument(
"--log-x", help="Use a logarithmic x (parameter) axis", action="store_true" "--log-x", help="Use a logarithmic x (parameter) axis", action="store_true"
) )
parser.add_argument( parser.add_argument(
"--log-y", "--log-y",
"--log-time", "--log-time",
dest="log_y", dest="log_y",
help="Use a logarithmic metric axis", help="Use a logarithmic metric axis",
action="store_true", action="store_true",
) )
parser.add_argument( parser.add_argument(
"--titles", help="Comma-separated list of titles for the plot legend" "--titles", help="Comma-separated list of titles for the plot legend"
) )
parser.add_argument("-o", "--output", help="Save image to the given filename.") parser.add_argument("-o", "--output", help="Save image to the given filename.")
args = parser.parse_args() args = parser.parse_args()
metric, datasets = load_results(parser, args.file, args.metric) metric, datasets = load_results(parser, args.file, args.metric)
metric_info = METRICS[metric] metric_info = METRICS[metric]
if args.parameter_name is not None: if args.parameter_name is not None:
sys.stderr.write( sys.stderr.write(
"warning: --parameter-name is deprecated; names are inferred from " "warning: --parameter-name is deprecated; names are inferred from "
"benchmark results\n" "benchmark results\n"
) )
def die(msg):
def die(msg):
sys.stderr.write(f"fatal: {msg}\n") sys.stderr.write(f"fatal: {msg}\n")
sys.exit(1) sys.exit(1)
def extract_parameters(results):
def extract_parameters(results):
"""Return `(parameter_name: str, parameter_values: List[float])`.""" """Return `(parameter_name: str, parameter_values: List[float])`."""
if not results: if not results:
die("no benchmark data to plot") die("no benchmark data to plot")
@@ -68,8 +68,7 @@ def extract_parameters(results):
) )
return (next(iter(names)), list(values)) return (next(iter(names)), list(values))
def unique_parameter(benchmark):
def unique_parameter(benchmark):
"""Return the unique parameter `(name: str, value: float)`, or die.""" """Return the unique parameter `(name: str, value: float)`, or die."""
params_dict = benchmark.get("parameters", {}) params_dict = benchmark.get("parameters", {})
if not params_dict: if not params_dict:
@@ -81,10 +80,9 @@ def unique_parameter(benchmark):
[(name, value)] = params_dict.items() [(name, value)] = params_dict.items()
return (name, float(value["value"])) return (name, float(value["value"]))
parameter_name = None
parameter_name = None for results in datasets:
for results in datasets:
(this_parameter_name, parameter_values) = extract_parameters(results) (this_parameter_name, parameter_values) = extract_parameters(results)
if parameter_name is not None and this_parameter_name != parameter_name: if parameter_name is not None and this_parameter_name != parameter_name:
die( die(
@@ -101,21 +99,25 @@ for results in datasets:
plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2) plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2)
plt.xlabel(parameter_name) plt.xlabel(parameter_name)
plt.ylabel(metric_info.axis_label) plt.ylabel(metric_info.axis_label)
if args.log_y: if args.log_y:
plt.yscale("log") plt.yscale("log")
else: else:
plt.ylim(0, None) plt.ylim(0, None)
if args.log_x: if args.log_x:
plt.xscale("log") plt.xscale("log")
if args.titles: if args.titles:
plt.legend(args.titles.split(",")) plt.legend(args.titles.split(","))
if args.output: if args.output:
plt.savefig(args.output) plt.savefig(args.output)
else: else:
plt.show() plt.show()
if __name__ == "__main__":
main()
+28 -23
View File
@@ -29,32 +29,33 @@ def moving_average(values, num_runs):
return np.convolve(values_padded, kernel, mode="valid") return np.convolve(values_padded, kernel, mode="valid")
parser = argparse.ArgumentParser(description=__doc__) def main():
add_metric_argument(parser) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("file", help="JSON file with benchmark results") add_metric_argument(parser)
parser.add_argument("--title", help="Plot Title") parser.add_argument("file", help="JSON file with benchmark results")
parser.add_argument("-o", "--output", help="Save image to the given filename.") parser.add_argument("--title", help="Plot Title")
parser.add_argument( parser.add_argument("-o", "--output", help="Save image to the given filename.")
parser.add_argument(
"-w", "-w",
"--moving-average-width", "--moving-average-width",
type=int, type=int,
metavar="num_runs", metavar="num_runs",
help="Width of the moving-average window (default: N/5)", help="Width of the moving-average window (default: N/5)",
) )
parser.add_argument( parser.add_argument(
"--no-moving-average", "--no-moving-average",
action="store_true", action="store_true",
help="Do not show moving average curve", help="Do not show moving average curve",
) )
args = parser.parse_args()
metric, [results] = load_results(parser, [args.file], args.metric)
metric_info = METRICS[metric]
args = parser.parse_args() for result in results:
metric, [results] = load_results(parser, [args.file], args.metric) values = [
metric_info = METRICS[metric] m[metric]["value"] / metric_info.scale for m in result["measurements"]
]
for result in results:
label = result.get("name", result["command"])
values = [m[metric]["value"] / metric_info.scale for m in result["measurements"]]
num = len(values) num = len(values)
nums = range(num) nums = range(num)
@@ -72,19 +73,23 @@ for result in results:
average = moving_average(values, moving_average_width) average = moving_average(values, moving_average_width)
plt.plot(nums, average, "-") plt.plot(nums, average, "-")
if args.title: if args.title:
plt.title(args.title) plt.title(args.title)
legend = [] legend = []
for result in results: for result in results:
legend.append(result.get("name", result["command"])) legend.append(result.get("name", result["command"]))
if not args.no_moving_average: if not args.no_moving_average:
legend.append("moving average") legend.append("moving average")
plt.legend(legend) plt.legend(legend)
plt.ylabel(metric_info.axis_label) plt.ylabel(metric_info.axis_label)
if args.output: if args.output:
plt.savefig(args.output) plt.savefig(args.output)
else: else:
plt.show() plt.show()
if __name__ == "__main__":
main()
+36 -29
View File
@@ -21,49 +21,56 @@ import matplotlib.pyplot as plt
from plot_utils import METRICS, add_metric_argument, load_results from plot_utils import METRICS, add_metric_argument, load_results
parser = argparse.ArgumentParser(description=__doc__)
add_metric_argument(parser) def main():
parser.add_argument("file", help="JSON file with benchmark results") parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--title", help="Plot Title") add_metric_argument(parser)
parser.add_argument("--sort-by", choices=["median"], help="Sort method") parser.add_argument("file", help="JSON file with benchmark results")
parser.add_argument( parser.add_argument("--title", help="Plot Title")
parser.add_argument("--sort-by", choices=["median"], help="Sort method")
parser.add_argument(
"--labels", help="Comma-separated list of entries for the plot legend" "--labels", help="Comma-separated list of entries for the plot legend"
) )
parser.add_argument("-o", "--output", help="Save image to the given filename.") parser.add_argument("-o", "--output", help="Save image to the given filename.")
args = parser.parse_args() args = parser.parse_args()
metric, [results] = load_results(parser, [args.file], args.metric) metric, [results] = load_results(parser, [args.file], args.metric)
metric_info = METRICS[metric] metric_info = METRICS[metric]
if args.labels: if args.labels:
labels = args.labels.split(",") labels = args.labels.split(",")
else: else:
labels = [b.get("name", b["command"]) for b in results] labels = [b.get("name", b["command"]) for b in results]
values = [ values = [
[m[metric]["value"] / metric_info.scale for m in b["measurements"]] for b in results [m[metric]["value"] / metric_info.scale for m in b["measurements"]]
] for b in results
]
if args.sort_by == "median": if args.sort_by == "median":
medians = [b["summary"][metric]["median"] for b in results] medians = [b["summary"][metric]["median"] for b in results]
indices = sorted(range(len(labels)), key=lambda k: medians[k]) indices = sorted(range(len(labels)), key=lambda k: medians[k])
labels = [labels[i] for i in indices] labels = [labels[i] for i in indices]
values = [values[i] for i in indices] values = [values[i] for i in indices]
plt.figure(figsize=(10, 6), constrained_layout=True) plt.figure(figsize=(10, 6), constrained_layout=True)
boxplot = plt.boxplot(values, vert=True, patch_artist=True) boxplot = plt.boxplot(values, vert=True, patch_artist=True)
cmap = plt.get_cmap("rainbow") cmap = plt.get_cmap("rainbow")
colors = [cmap(val / len(values)) for val in range(len(values))] colors = [cmap(val / len(values)) for val in range(len(values))]
for patch, color in zip(boxplot["boxes"], colors): for patch, color in zip(boxplot["boxes"], colors):
patch.set_facecolor(color) patch.set_facecolor(color)
if args.title: if args.title:
plt.title(args.title) plt.title(args.title)
plt.legend(handles=boxplot["boxes"], labels=labels, loc="best", fontsize="medium") plt.legend(handles=boxplot["boxes"], labels=labels, loc="best", fontsize="medium")
plt.ylabel(metric_info.axis_label) plt.ylabel(metric_info.axis_label)
plt.ylim(0, None) plt.ylim(0, None)
plt.xticks(list(range(1, len(labels) + 1)), labels, rotation=45) plt.xticks(list(range(1, len(labels) + 1)), labels, rotation=45)
if args.output: if args.output:
plt.savefig(args.output) plt.savefig(args.output)
else: else:
plt.show() plt.show()
if __name__ == "__main__":
main()
+26 -20
View File
@@ -16,38 +16,44 @@ from scipy import stats
from plot_utils import METRICS, add_metric_argument, load_results from plot_utils import METRICS, add_metric_argument, load_results
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("file", help="JSON file with two benchmark results")
add_metric_argument(parser)
args = parser.parse_args()
metric, [results] = load_results(parser, [args.file], args.metric) def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("file", help="JSON file with two benchmark results")
add_metric_argument(parser)
args = parser.parse_args()
if len(results) != 2: metric, [results] = load_results(parser, [args.file], args.metric)
if len(results) != 2:
parser.error("the input file must contain exactly two benchmarks") parser.error("the input file must contain exactly two benchmarks")
a, b = (x.get("name", x["command"]) for x in results[:2]) a, b = (x.get("name", x["command"]) for x in results[:2])
X, Y = ([m[metric]["value"] for m in x["measurements"]] for x in results[:2]) X, Y = ([m[metric]["value"] for m in x["measurements"]] for x in results[:2])
if min(len(X), len(Y)) < 2: if min(len(X), len(Y)) < 2:
parser.error("Welch's t-test requires at least two measurements per benchmark") parser.error("Welch's t-test requires at least two measurements per benchmark")
print(f"Metric: {METRICS[metric].label}") print(f"Metric: {METRICS[metric].label}")
print(f"Command 1: {a}") print(f"Command 1: {a}")
print(f"Command 2: {b}\n") print(f"Command 2: {b}\n")
t, p = stats.ttest_ind(X, Y, equal_var=False) t, p = stats.ttest_ind(X, Y, equal_var=False)
if not math.isfinite(p): if not math.isfinite(p):
parser.error("Welch's t-test is undefined for these measurements") parser.error("Welch's t-test is undefined for these measurements")
th = 0.05 th = 0.05
dispose = p < th dispose = p < th
print(f"t = {t:.3}, p = {p:.3}") print(f"t = {t:.3}, p = {p:.3}")
print() print()
if dispose: if dispose:
print( print(
f"A statistically significant difference in mean value was detected (p < {th})." f"A statistically significant difference in mean value was detected (p < {th})."
) )
else: else:
print( print(
f"No statistically significant difference in mean value was detected (p >= {th})." f"No statistically significant difference in mean value was detected (p >= {th})."
) )
if __name__ == "__main__":
main()