Make plotting scripts runnable with uv
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Peter · committed by David Peter · parent 4a9e066 · Browse files · 10 files·+498 added−406 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+498 added−406 removed
- other:+498 added−406 removed
Provenance
- Commit
ce49529- Tree
9a2082c- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
4a9e066
10 files changed+498 added−406 removed
modified:scripts/advanced_statistics.py+44 added-40 removed
10 unmodified lines11 import numpy as np12 13 from plot_utils import METRICS, add_metric_argument, load_results14 15-parser = argparse.ArgumentParser()16-parser.add_argument("file", help="JSON file with benchmark results")17-add_metric_argument(parser)18-parser.add_argument(19- "--time-unit",20- help="Display unit for time metrics (default: second).",21- choices=["second", "millisecond"],22-)23-args = parser.parse_args()15 25-metric, [results] = load_results(parser, [args.file], args.metric)26-description = METRICS[metric]27-unit, scale = description.unit, description.scale28-if 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.00116+def main():17+ parser = argparse.ArgumentParser()18+ parser.add_argument("file", help="JSON file with benchmark results")19+ add_metric_argument(parser)20+ parser.add_argument(21+ "--time-unit",22+ help="Display unit for time metrics (default: second).",23+ choices=["second", "millisecond"],24+ )25+ args = parser.parse_args()26 27+ metric, [results] = load_results(parser, [args.file], args.metric)28+ description = METRICS[metric]29+ unit, scale = description.unit, description.scale30+ if args.time_unit is not None:31+ if not metric.startswith("time_"):32+ parser.error("--time-unit can only be used with a time metric")33+ if args.time_unit == "millisecond":34+ unit, scale = "ms", 0.00135 35-def format_value(value):36- suffix = f" {unit}" if unit else ""37- return f"{value:.3f}{suffix}"36+ def format_value(value):37+ suffix = f" {unit}" if unit else ""38+ return f"{value:.3f}{suffix}"39 40+ print(f"Metric: {description.label}\n")41+ for result in results:42+ summary = result["summary"][metric]43+ values = [m[metric]["value"] / scale for m in result["measurements"]]44 40-print(f"Metric: {description.label}\n")41-for result in results:42- summary = result["summary"][metric]43- values = [m[metric]["value"] / scale for m in result["measurements"]]45+ p05, p25, p75, p95 = np.percentile(values, [5, 25, 75, 95])46 45- p05, p25, p75, p95 = np.percentile(values, [5, 25, 75, 95])47+ iqr = p75 - p2548 47- iqr = p75 - p2549+ print(f"Command '{result.get('name', result['command'])}'")50+ print(f" runs: {summary['count']:8d}")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:")57+ print(f" P_05 .. P_95: {format_value(p05)} .. {format_value(p95)}")58+ print(59+ f" P_25 .. P_75: {format_value(p25)} .. {format_value(p75)}"60+ f" (IQR = {format_value(iqr)})"61+ )62+ print()63 49- print(f"Command '{result.get('name', result['command'])}'")50- print(f" runs: {summary['count']:8d}")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:")57- print(f" P_05 .. P_95: {format_value(p05)} .. {format_value(p95)}")58- print(59- f" P_25 .. P_75: {format_value(p25)} .. {format_value(p75)}"60- f" (IQR = {format_value(iqr)})"61- )62- print()64+65+if __name__ == "__main__":66+ main()modified:scripts/plot_benchmark_comparison.py+58 added-52 removed
19 unmodified lines20 import numpy as np21 22 from plot_utils import METRICS, add_metric_argument, load_results23 24-parser = argparse.ArgumentParser(description=__doc__)25-add_metric_argument(parser)26-parser.add_argument(27- "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"28-)29-parser.add_argument("--title", help="Plot Title")30-parser.add_argument(31- "--benchmark-names", nargs="+", help="Names of the benchmark groups"32-)33-parser.add_argument("-o", "--output", help="Save image to the given filename")24 35-args = parser.parse_args()36-metric, datasets = load_results(parser, args.files, args.metric)37-metric_info = METRICS[metric]25+def main():26+ parser = argparse.ArgumentParser(description=__doc__)27+ add_metric_argument(parser)28+ parser.add_argument(29+ "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"30+ )31+ parser.add_argument("--title", help="Plot Title")32+ parser.add_argument(33+ "--benchmark-names", nargs="+", help="Names of the benchmark groups"34+ )35+ parser.add_argument("-o", "--output", help="Save image to the given filename")36 39-commands = None40-data = []41-inputs = []37+ args = parser.parse_args()38+ metric, datasets = load_results(parser, args.files, args.metric)39+ metric_info = METRICS[metric]40 43-if args.benchmark_names:44- assert len(args.files) == len(args.benchmark_names), (45- "Number of benchmark names must match the number of input files."46- )41+ commands = None42+ data = []43+ inputs = []44 48-for 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- )56- data.append([b["summary"][metric]["mean"] / metric_info.scale for b in results])45 if args.benchmark_names:58- inputs.append(args.benchmark_names[i])59- else:60- inputs.append(filename.stem)46+ assert len(args.files) == len(args.benchmark_names), (47+ "Number of benchmark names must match the number of input files."48+ )49 62-data = np.transpose(data)63-x = np.arange(len(inputs)) # the label locations64-width = 0.25 # the width of the bars50+ for i, (filename, results) in enumerate(zip(args.files, datasets)):51+ benchmark_commands = [b.get("name", b["command"]) for b in results]52+ if commands is None:53+ commands = benchmark_commands54+ else:55+ assert commands == benchmark_commands, (56+ f"Unexpected commands in {filename}: {benchmark_commands}, expected: {commands}"57+ )58+ data.append([b["summary"][metric]["mean"] / metric_info.scale for b in results])59+ if args.benchmark_names:60+ inputs.append(args.benchmark_names[i])61+ else:62+ inputs.append(filename.stem)63 66-fig, ax = plt.subplots(layout="constrained")67-fig.set_figheight(5)68-fig.set_figwidth(10)69-for i, command in enumerate(commands):70- offset = width * (i + 1)71- rects = ax.bar(x + offset, data[i], width, label=command)64+ data = np.transpose(data)65+ x = np.arange(len(inputs)) # the label locations66+ width = 0.25 # the width of the bars67 73-ax.set_xticks(x + 0.5, inputs)74-ax.grid(visible=True, axis="y")68+ fig, ax = plt.subplots(layout="constrained")69+ fig.set_figheight(5)70+ fig.set_figwidth(10)71+ for i, command in enumerate(commands):72+ offset = width * (i + 1)73+ ax.bar(x + offset, data[i], width, label=command)74 76-if args.title:77- plt.title(args.title)78-plt.xlabel("Benchmark")79-plt.ylabel(metric_info.axis_label)80-plt.legend(title="Command")75+ ax.set_xticks(x + 0.5, inputs)76+ ax.grid(visible=True, axis="y")77 78+ if args.title:79+ plt.title(args.title)80+ plt.xlabel("Benchmark")81+ plt.ylabel(metric_info.axis_label)82+ plt.legend(title="Command")83+82-if args.output:83- plt.savefig(args.output)84-else:85- plt.show()84+ if args.output:85+ plt.savefig(args.output)86+ else:87+ plt.show()88+89+90+if __name__ == "__main__":91+ main()modified:scripts/plot_histogram.py+104 added-97 removed
15 unmodified lines16 import numpy as np17 18 from plot_utils import METRICS, add_metric_argument, load_results19 20-parser = argparse.ArgumentParser(description=__doc__)21-add_metric_argument(parser)22-parser.add_argument("file", help="JSON file with benchmark results")23-parser.add_argument("--title", help="Plot title")24-parser.add_argument(25- "--labels", help="Comma-separated list of entries for the plot legend"26-)27-parser.add_argument("--bins", help="Number of bins (default: auto)")28-parser.add_argument(29- "--legend-location",30- help="Location of the legend on plot (default: upper center)",31- choices=[32- "upper center",33- "lower center",34- "right",35- "left",36- "best",37- "upper left",38- "upper right",39- "lower left",40- "lower right",41- "center left",42- "center right",43- "center",44- ],45- default="upper center",46-)47-parser.add_argument(48- "--type", help="Type of histogram (*bar*, barstacked, step, stepfilled)"49-)50-parser.add_argument("-o", "--output", help="Save image to the given filename.")51-parser.add_argument(52- "--min",53- "--t-min",54- dest="value_min",55- type=float,56- help="Minimum metric value to display",57-)58-parser.add_argument(59- "--max",60- "--t-max",61- dest="value_max",62- type=float,63- help="Maximum metric value to display",64-)65-parser.add_argument(66- "--log-count",67- help="Use a logarithmic y-axis for the event count",68- action="store_true",69-)20 71-args = parser.parse_args()72-metric, [results] = load_results(parser, [args.file], args.metric)73-metric_info = METRICS[metric]21+def main():22+ parser = argparse.ArgumentParser(description=__doc__)23+ add_metric_argument(parser)24+ parser.add_argument("file", help="JSON file with benchmark results")25+ parser.add_argument("--title", help="Plot title")26+ parser.add_argument(27+ "--labels", help="Comma-separated list of entries for the plot legend"28+ )29+ parser.add_argument("--bins", help="Number of bins (default: auto)")30+ parser.add_argument(31+ "--legend-location",32+ help="Location of the legend on plot (default: upper center)",33+ choices=[34+ "upper center",35+ "lower center",36+ "right",37+ "left",38+ "best",39+ "upper left",40+ "upper right",41+ "lower left",42+ "lower right",43+ "center left",44+ "center right",45+ "center",46+ ],47+ default="upper center",48+ )49+ parser.add_argument(50+ "--type", help="Type of histogram (*bar*, barstacked, step, stepfilled)"51+ )52+ parser.add_argument("-o", "--output", help="Save image to the given filename.")53+ parser.add_argument(54+ "--min",55+ "--t-min",56+ dest="value_min",57+ type=float,58+ help="Minimum metric value to display",59+ )60+ parser.add_argument(61+ "--max",62+ "--t-max",63+ dest="value_max",64+ type=float,65+ help="Maximum metric value to display",66+ )67+ parser.add_argument(68+ "--log-count",69+ help="Use a logarithmic y-axis for the event count",70+ action="store_true",71+ )72 75-if args.labels:76- labels = args.labels.split(",")77-else:78- labels = [b.get("name", b["command"]) for b in results]79-all_values = [80- [m[metric]["value"] / metric_info.scale for m in b["measurements"]] for b in results81-]73+ args = parser.parse_args()74+ metric, [results] = load_results(parser, [args.file], args.metric)75+ metric_info = METRICS[metric]76 83-value_min = (84- args.value_min85- if args.value_min is not None86- else np.min(list(map(np.min, all_values)))87-)88-value_max = (89- args.value_max90- if args.value_max is not None91- else np.max(list(map(np.max, all_values)))92-)77+ if args.labels:78+ labels = args.labels.split(",")79+ else:80+ labels = [b.get("name", b["command"]) for b in results]81+ all_values = [82+ [m[metric]["value"] / metric_info.scale for m in b["measurements"]]83+ for b in results84+ ]85 94-bins = int(args.bins) if args.bins else "auto"95-histtype = args.type if args.type else "bar"86+ value_min = (87+ args.value_min88+ if args.value_min is not None89+ else np.min(list(map(np.min, all_values)))90+ )91+ value_max = (92+ args.value_max93+ if args.value_max is not None94+ else np.max(list(map(np.max, all_values)))95+ )96 97-plt.figure(figsize=(10, 5))98-plt.hist(99- all_values,100- label=labels,101- bins=bins,102- histtype=histtype,103- range=(value_min, value_max),104-)105-plt.legend(106- loc=args.legend_location,107- fancybox=True,108- shadow=True,109- prop={"size": 10, "family": ["Source Code Pro", "Fira Mono", "Courier New"]},110-)97+ bins = int(args.bins) if args.bins else "auto"98+ histtype = args.type if args.type else "bar"99 112-plt.xlabel(metric_info.axis_label)113-if args.title:114- plt.title(args.title)100+ plt.figure(figsize=(10, 5))101+ plt.hist(102+ all_values,103+ label=labels,104+ bins=bins,105+ histtype=histtype,106+ range=(value_min, value_max),107+ )108+ plt.legend(109+ loc=args.legend_location,110+ fancybox=True,111+ shadow=True,112+ prop={"size": 10, "family": ["Source Code Pro", "Fira Mono", "Courier New"]},113+ )114 116-if args.log_count:117- plt.yscale("log")118-else:119- plt.ylim(0, None)115+ plt.xlabel(metric_info.axis_label)116+ if args.title:117+ plt.title(args.title)118 119+ if args.log_count:120+ plt.yscale("log")121+ else:122+ plt.ylim(0, None)123+121-if args.output:122- plt.savefig(args.output, dpi=600)123-else:124- plt.show()124+ if args.output:125+ plt.savefig(args.output, dpi=600)126+ else:127+ plt.show()128+129+130+if __name__ == "__main__":131+ main()modified:scripts/plot_parametrized.py+87 added-85 removed
15 unmodified lines16 import matplotlib.pyplot as plt17 18 from plot_utils import METRICS, add_metric_argument, load_results19 20-parser = argparse.ArgumentParser(description=__doc__)21-add_metric_argument(parser)22-parser.add_argument("file", help="JSON file with benchmark results", nargs="+")23-parser.add_argument(24- "--parameter-name",25- metavar="name",26- type=str,27- help="Deprecated; parameter names are now inferred from benchmark files",28-)29-parser.add_argument(30- "--log-x", help="Use a logarithmic x (parameter) axis", action="store_true"31-)32-parser.add_argument(33- "--log-y",34- "--log-time",35- dest="log_y",36- help="Use a logarithmic metric axis",37- action="store_true",38-)39-parser.add_argument(40- "--titles", help="Comma-separated list of titles for the plot legend"41-)42-parser.add_argument("-o", "--output", help="Save image to the given filename.")20 44-args = parser.parse_args()45-metric, datasets = load_results(parser, args.file, args.metric)46-metric_info = METRICS[metric]47-if args.parameter_name is not None:48- sys.stderr.write(49- "warning: --parameter-name is deprecated; names are inferred from "50- "benchmark results\n"21+def main():22+ parser = argparse.ArgumentParser(description=__doc__)23+ add_metric_argument(parser)24+ parser.add_argument("file", help="JSON file with benchmark results", nargs="+")25+ parser.add_argument(26+ "--parameter-name",27+ metavar="name",28+ type=str,29+ help="Deprecated; parameter names are now inferred from benchmark files",30 )31+ parser.add_argument(32+ "--log-x", help="Use a logarithmic x (parameter) axis", action="store_true"33+ )34+ parser.add_argument(35+ "--log-y",36+ "--log-time",37+ dest="log_y",38+ help="Use a logarithmic metric axis",39+ action="store_true",40+ )41+ parser.add_argument(42+ "--titles", help="Comma-separated list of titles for the plot legend"43+ )44+ parser.add_argument("-o", "--output", help="Save image to the given filename.")45 46+ args = parser.parse_args()47+ metric, datasets = load_results(parser, args.file, args.metric)48+ metric_info = METRICS[metric]49+ if args.parameter_name is not None:50+ sys.stderr.write(51+ "warning: --parameter-name is deprecated; names are inferred from "52+ "benchmark results\n"53+ )54 54-def die(msg):55- sys.stderr.write(f"fatal: {msg}\n")56- sys.exit(1)55+ def die(msg):56+ sys.stderr.write(f"fatal: {msg}\n")57+ sys.exit(1)58 59+ def extract_parameters(results):60+ """Return `(parameter_name: str, parameter_values: List[float])`."""61+ if not results:62+ die("no benchmark data to plot")63+ (names, values) = zip(*(unique_parameter(b) for b in results))64+ names = frozenset(names)65+ if len(names) != 1:66+ die(67+ f"benchmarks must all have the same parameter name, but found: {sorted(names)}"68+ )69+ return (next(iter(names)), list(values))70 59-def extract_parameters(results):60- """Return `(parameter_name: str, parameter_values: List[float])`."""61- if not results:62- die("no benchmark data to plot")63- (names, values) = zip(*(unique_parameter(b) for b in results))64- names = frozenset(names)65- if len(names) != 1:66- die(67- f"benchmarks must all have the same parameter name, but found: {sorted(names)}"68- )69- return (next(iter(names)), list(values))71+ def unique_parameter(benchmark):72+ """Return the unique parameter `(name: str, value: float)`, or die."""73+ params_dict = benchmark.get("parameters", {})74+ if not params_dict:75+ die("benchmarks must have exactly one parameter, but found none")76+ if len(params_dict) > 1:77+ die(78+ f"benchmarks must have exactly one parameter, but found multiple: {sorted(params_dict)}"79+ )80+ [(name, value)] = params_dict.items()81+ return (name, float(value["value"]))82 83+ parameter_name = None84 72-def unique_parameter(benchmark):73- """Return the unique parameter `(name: str, value: float)`, or die."""74- params_dict = benchmark.get("parameters", {})75- if not params_dict:76- die("benchmarks must have exactly one parameter, but found none")77- if len(params_dict) > 1:78- die(79- f"benchmarks must have exactly one parameter, but found multiple: {sorted(params_dict)}"80- )81- [(name, value)] = params_dict.items()82- return (name, float(value["value"]))85+ for results in datasets:86+ (this_parameter_name, parameter_values) = extract_parameters(results)87+ if parameter_name is not None and this_parameter_name != parameter_name:88+ die(89+ f"files must all have the same parameter name, but found {parameter_name!r} vs. {this_parameter_name!r}"90+ )91+ parameter_name = this_parameter_name92 93+ summaries = [b["summary"][metric] for b in results]94+ means = [s["mean"] / metric_info.scale for s in summaries]95+ stddevs = [96+ s["stddev"] / metric_info.scale if s["stddev"] is not None else float("nan")97+ for s in summaries98+ ]99 85-parameter_name = None100+ plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2)101 87-for 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_name102+ plt.xlabel(parameter_name)103+ plt.ylabel(metric_info.axis_label)104 95- summaries = [b["summary"][metric] for b in results]96- means = [s["mean"] / metric_info.scale for s in summaries]97- stddevs = [98- s["stddev"] / metric_info.scale if s["stddev"] is not None else float("nan")99- for s in summaries100- ]105+ if args.log_y:106+ plt.yscale("log")107+ else:108+ plt.ylim(0, None)109 102- plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2)110+ if args.log_x:111+ plt.xscale("log")112 104-plt.xlabel(parameter_name)105-plt.ylabel(metric_info.axis_label)113+ if args.titles:114+ plt.legend(args.titles.split(","))115 107-if args.log_y:108- plt.yscale("log")109-else:110- plt.ylim(0, None)116+ if args.output:117+ plt.savefig(args.output)118+ else:119+ plt.show()120 112-if args.log_x:113- plt.xscale("log")121 115-if args.titles:116- plt.legend(args.titles.split(","))117-118-if args.output:119- plt.savefig(args.output)120-else:121- plt.show()122+if __name__ == "__main__":123+ main()modified:scripts/plot_progression.py+54 added-49 removed
27 unmodified lines28 kernel = np.ones(num_runs) / num_runs29 return np.convolve(values_padded, kernel, mode="valid")30 31 32+def main():32-parser = argparse.ArgumentParser(description=__doc__)33-add_metric_argument(parser)34-parser.add_argument("file", help="JSON file with benchmark results")35-parser.add_argument("--title", help="Plot Title")36-parser.add_argument("-o", "--output", help="Save image to the given filename.")37-parser.add_argument(38- "-w",39- "--moving-average-width",40- type=int,41- metavar="num_runs",42- help="Width of the moving-average window (default: N/5)",43-)44-parser.add_argument(45- "--no-moving-average",46- action="store_true",47- help="Do not show moving average curve",48-)33+ parser = argparse.ArgumentParser(description=__doc__)34+ add_metric_argument(parser)35+ parser.add_argument("file", help="JSON file with benchmark results")36+ parser.add_argument("--title", help="Plot Title")37+ parser.add_argument("-o", "--output", help="Save image to the given filename.")38+ parser.add_argument(39+ "-w",40+ "--moving-average-width",41+ type=int,42+ metavar="num_runs",43+ help="Width of the moving-average window (default: N/5)",44+ )45+ parser.add_argument(46+ "--no-moving-average",47+ action="store_true",48+ help="Do not show moving average curve",49+ )50 51+ args = parser.parse_args()52+ metric, [results] = load_results(parser, [args.file], args.metric)53+ metric_info = METRICS[metric]54 51-args = parser.parse_args()52-metric, [results] = load_results(parser, [args.file], args.metric)53-metric_info = METRICS[metric]55+ for result in results:56+ values = [57+ m[metric]["value"] / metric_info.scale for m in result["measurements"]58+ ]59+ num = len(values)60+ nums = range(num)61 55-for result in results:56- label = result.get("name", result["command"])57- values = [m[metric]["value"] / metric_info.scale for m in result["measurements"]]58- num = len(values)59- nums = range(num)62+ plt.scatter(x=nums, y=values, marker=".")63+ plt.ylim([0, None])64+ plt.xlim([-1, num])65 61- plt.scatter(x=nums, y=values, marker=".")62- plt.ylim([0, None])63- plt.xlim([-1, num])66+ if not args.no_moving_average:67+ moving_average_width = (68+ max(1, num // 5)69+ if args.moving_average_width is None70+ else args.moving_average_width71+ )72 65- if not args.no_moving_average:66- moving_average_width = (67- max(1, num // 5)68- if args.moving_average_width is None69- else args.moving_average_width70- )73+ average = moving_average(values, moving_average_width)74+ plt.plot(nums, average, "-")75 72- average = moving_average(values, moving_average_width)73- plt.plot(nums, average, "-")76+ if args.title:77+ plt.title(args.title)78 75-if args.title:76- plt.title(args.title)79+ legend = []80+ for result in results:81+ legend.append(result.get("name", result["command"]))82+ if not args.no_moving_average:83+ legend.append("moving average")84+ plt.legend(legend)85 78-legend = []79-for result in results:80- legend.append(result.get("name", result["command"]))81- if not args.no_moving_average:82- legend.append("moving average")83-plt.legend(legend)86+ plt.ylabel(metric_info.axis_label)87 85-plt.ylabel(metric_info.axis_label)88+ if args.output:89+ plt.savefig(args.output)90+ else:91+ plt.show()92 87-if args.output:88- plt.savefig(args.output)89-else:90- plt.show()93+94+if __name__ == "__main__":95+ main()modified:scripts/plot_whisker.py+47 added-40 removed
19 unmodified lines20 import matplotlib.pyplot as plt21 22 from plot_utils import METRICS, add_metric_argument, load_results23 24-parser = argparse.ArgumentParser(description=__doc__)25-add_metric_argument(parser)26-parser.add_argument("file", help="JSON file with benchmark results")27-parser.add_argument("--title", help="Plot Title")28-parser.add_argument("--sort-by", choices=["median"], help="Sort method")29-parser.add_argument(30- "--labels", help="Comma-separated list of entries for the plot legend"31-)32-parser.add_argument("-o", "--output", help="Save image to the given filename.")24 34-args = parser.parse_args()35-metric, [results] = load_results(parser, [args.file], args.metric)36-metric_info = METRICS[metric]25+def main():26+ parser = argparse.ArgumentParser(description=__doc__)27+ add_metric_argument(parser)28+ parser.add_argument("file", help="JSON file with benchmark results")29+ parser.add_argument("--title", help="Plot Title")30+ parser.add_argument("--sort-by", choices=["median"], help="Sort method")31+ parser.add_argument(32+ "--labels", help="Comma-separated list of entries for the plot legend"33+ )34+ parser.add_argument("-o", "--output", help="Save image to the given filename.")35 38-if args.labels:39- labels = args.labels.split(",")40-else:41- labels = [b.get("name", b["command"]) for b in results]42-values = [43- [m[metric]["value"] / metric_info.scale for m in b["measurements"]] for b in results44-]36+ args = parser.parse_args()37+ metric, [results] = load_results(parser, [args.file], args.metric)38+ metric_info = METRICS[metric]39 46-if args.sort_by == "median":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]40+ if args.labels:41+ labels = args.labels.split(",")42+ else:43+ labels = [b.get("name", b["command"]) for b in results]44+ values = [45+ [m[metric]["value"] / metric_info.scale for m in b["measurements"]]46+ for b in results47+ ]48 52-plt.figure(figsize=(10, 6), constrained_layout=True)53-boxplot = plt.boxplot(values, vert=True, patch_artist=True)54-cmap = plt.get_cmap("rainbow")55-colors = [cmap(val / len(values)) for val in range(len(values))]49+ if args.sort_by == "median":50+ medians = [b["summary"][metric]["median"] for b in results]51+ indices = sorted(range(len(labels)), key=lambda k: medians[k])52+ labels = [labels[i] for i in indices]53+ values = [values[i] for i in indices]54 57-for patch, color in zip(boxplot["boxes"], colors):58- patch.set_facecolor(color)55+ plt.figure(figsize=(10, 6), constrained_layout=True)56+ boxplot = plt.boxplot(values, vert=True, patch_artist=True)57+ cmap = plt.get_cmap("rainbow")58+ colors = [cmap(val / len(values)) for val in range(len(values))]59 60+ for patch, color in zip(boxplot["boxes"], colors):61+ patch.set_facecolor(color)62+60-if args.title:61- plt.title(args.title)62-plt.legend(handles=boxplot["boxes"], labels=labels, loc="best", fontsize="medium")63-plt.ylabel(metric_info.axis_label)64-plt.ylim(0, None)65-plt.xticks(list(range(1, len(labels) + 1)), labels, rotation=45)66-if args.output:67- plt.savefig(args.output)68-else:69- plt.show()63+ if args.title:64+ plt.title(args.title)65+ plt.legend(handles=boxplot["boxes"], labels=labels, loc="best", fontsize="medium")66+ plt.ylabel(metric_info.axis_label)67+ plt.ylim(0, None)68+ plt.xticks(list(range(1, len(labels) + 1)), labels, rotation=45)69+ if args.output:70+ plt.savefig(args.output)71+ else:72+ plt.show()73+74+75+if __name__ == "__main__":76+ main()modified:scripts/README.md+23 added-13 removed
123345678971011121310141512131416171819202122232425162627282918192021222330313233This 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/), thenrun one of the scripts:
```bashhyperfine 'sleep 0.020' 'sleep 0.021' 'sleep 0.022' --export-json sleep.jsonuv run plot_whisker.py sleep.jsonuvx --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.
```bashuv run plot_histogram.py benchmark.json --metric instructions```| 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 |
### PrerequisitesBy default, the plotting and analysis scripts use the metric that was selectedfirst in the actual hyperfine run (`--metrics` option).Use `--metric` to select another metric:
Install [`uv`](https://docs.astral.sh/uv/getting-started/installation/) and run thecommands 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 anisolated environment before running the script.```bashuvx --from 'git+https://github.com/sharkdp/hyperfine' \ plot_histogram benchmark.json --metric instructions```modified:scripts/welch_ttest.py+35 added-29 removed
14 unmodified lines15 from scipy import stats16 17 from plot_utils import METRICS, add_metric_argument, load_results18 19-parser = argparse.ArgumentParser(description=__doc__)20-parser.add_argument("file", help="JSON file with two benchmark results")21-add_metric_argument(parser)22-args = parser.parse_args()19 24-metric, [results] = load_results(parser, [args.file], args.metric)20+def main():21+ parser = argparse.ArgumentParser(description=__doc__)22+ parser.add_argument("file", help="JSON file with two benchmark results")23+ add_metric_argument(parser)24+ args = parser.parse_args()25 26-if len(results) != 2:27- parser.error("the input file must contain exactly two benchmarks")26+ metric, [results] = load_results(parser, [args.file], args.metric)27 29-a, b = (x.get("name", x["command"]) for x in results[:2])30-X, Y = ([m[metric]["value"] for m in x["measurements"]] for x in results[:2])31-if min(len(X), len(Y)) < 2:32- parser.error("Welch's t-test requires at least two measurements per benchmark")28+ if len(results) != 2:29+ parser.error("the input file must contain exactly two benchmarks")30 34-print(f"Metric: {METRICS[metric].label}")35-print(f"Command 1: {a}")36-print(f"Command 2: {b}\n")31+ a, b = (x.get("name", x["command"]) for x in results[:2])32+ X, Y = ([m[metric]["value"] for m in x["measurements"]] for x in results[:2])33+ if min(len(X), len(Y)) < 2:34+ parser.error("Welch's t-test requires at least two measurements per benchmark")35 38-t, p = stats.ttest_ind(X, Y, equal_var=False)39-if not math.isfinite(p):40- parser.error("Welch's t-test is undefined for these measurements")41-th = 0.0542-dispose = p < th43-print(f"t = {t:.3}, p = {p:.3}")44-print()36+ print(f"Metric: {METRICS[metric].label}")37+ print(f"Command 1: {a}")38+ print(f"Command 2: {b}\n")39 40+ t, p = stats.ttest_ind(X, Y, equal_var=False)41+ if not math.isfinite(p):42+ parser.error("Welch's t-test is undefined for these measurements")43+ th = 0.0544+ dispose = p < th45+ print(f"t = {t:.3}, p = {p:.3}")46+ print()47+46-if dispose:47- print(48- f"A statistically significant difference in mean value was detected (p < {th})."49- )50-else:51- print(52- f"No statistically significant difference in mean value was detected (p >= {th})."53- )48+ if dispose:49+ print(50+ f"A statistically significant difference in mean value was detected (p < {th})."51+ )52+ else:53+ print(54+ f"No statistically significant difference in mean value was detected (p >= {th})."55+ )56+57+58+if __name__ == "__main__":59+ main()added:pyproject.toml+36 added
1+[project]2+name = "hyperfine-scripts"3+version = "0.1.0"4+description = "Plot and analyze hyperfine JSON benchmark results"5+requires-python = ">=3.10"6+license-files = ["LICENSE-APACHE", "LICENSE-MIT"]7+dependencies = [8+ "matplotlib",9+ "numpy",10+ "pyqt6",11+ "scipy",12+]13+14+[project.scripts]15+advanced_statistics = "advanced_statistics:main"16+plot_benchmark_comparison = "plot_benchmark_comparison:main"17+plot_histogram = "plot_histogram:main"18+plot_parametrized = "plot_parametrized:main"19+plot_progression = "plot_progression:main"20+plot_whisker = "plot_whisker:main"21+welch_ttest = "welch_ttest:main"22+23+[tool.uv.build-backend]24+module-root = "scripts"25+module-name = ""26+namespace = true27+source-exclude = [28+ "/scripts/README.md",29+ "/scripts/ruff.toml",30+ "/scripts/.*",31+ "*.egg-info",32+]33+34+[build-system]35+requires = ["uv_build>=0.12.23,<0.13"]36+build-backend = "uv_build"modified:README.md+10 added-1 removed
255 unmodified lines256 The JSON output is useful if you want to analyze the benchmark results in more detail. The257 [`scripts/`](https://github.com/sharkdp/hyperfine/tree/master/scripts) folder includes a lot258 of helpful Python programs to further analyze benchmark results and create helpful259 visualizations, like a histogram of runtimes or a whisker plot to compare260-multiple benchmarks:260+multiple benchmarks.261 262+For example, these two commands create the following plots:263+264+```bash265+uvx --from 'git+https://github.com/sharkdp/hyperfine' \266+ plot_histogram results.json267+uvx --from 'git+https://github.com/sharkdp/hyperfine' \268+ plot_whisker results.json269+```270+271 |  |  |272 |---:|---:|273 274 184 unmodified lines