Skip to content
Myr

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

10 files+498 added−406 removed

modified:scripts/advanced_statistics.py+44 added-40 removed
10 unmodified lines
11import numpy as np1213from plot_utils import METRICS, add_metric_argument, load_results1415parser = argparse.ArgumentParser()16parser.add_argument("file", help="JSON file with benchmark results")17add_metric_argument(parser)18parser.add_argument(19 "--time-unit",20 help="Display unit for time metrics (default: second).",21 choices=["second", "millisecond"],22)23args = parser.parse_args()1525metric, [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.00116def 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()2627 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.0013535def 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}"3940 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"]]4440print(f"Metric: {description.label}\n")41for 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])4645 p05, p25, p75, p95 = np.percentile(values, [5, 25, 75, 95])47 iqr = p75 - p254847 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()6349 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()6465if __name__ == "__main__":66 main()
modified:scripts/plot_benchmark_comparison.py+58 added-52 removed
19 unmodified lines
20import numpy as np2122from plot_utils import METRICS, add_metric_argument, load_results2324parser = argparse.ArgumentParser(description=__doc__)25add_metric_argument(parser)26parser.add_argument(27 "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"28)29parser.add_argument("--title", help="Plot Title")30parser.add_argument(31 "--benchmark-names", nargs="+", help="Names of the benchmark groups"32)33parser.add_argument("-o", "--output", help="Save image to the given filename")2435args = parser.parse_args()36metric, datasets = load_results(parser, args.files, args.metric)37metric_info = METRICS[metric]25def 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")3639commands = None40data = []41inputs = []37 args = parser.parse_args()38 metric, datasets = load_results(parser, args.files, args.metric)39 metric_info = METRICS[metric]4043if 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 = []4448for 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 )4962data = np.transpose(data)63x = np.arange(len(inputs)) # the label locations64width = 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)6366fig, ax = plt.subplots(layout="constrained")67fig.set_figheight(5)68fig.set_figwidth(10)69for 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 bars6773ax.set_xticks(x + 0.5, inputs)74ax.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)7476if args.title:77 plt.title(args.title)78plt.xlabel("Benchmark")79plt.ylabel(metric_info.axis_label)80plt.legend(title="Command")75 ax.set_xticks(x + 0.5, inputs)76 ax.grid(visible=True, axis="y")7778 if args.title:79 plt.title(args.title)80 plt.xlabel("Benchmark")81 plt.ylabel(metric_info.axis_label)82 plt.legend(title="Command")8382if args.output:83 plt.savefig(args.output)84else:85 plt.show()84 if args.output:85 plt.savefig(args.output)86 else:87 plt.show()888990if __name__ == "__main__":91 main()
modified:scripts/plot_histogram.py+104 added-97 removed
15 unmodified lines
16import numpy as np1718from 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")23parser.add_argument("--title", help="Plot title")24parser.add_argument(25 "--labels", help="Comma-separated list of entries for the plot legend"26)27parser.add_argument("--bins", help="Number of bins (default: auto)")28parser.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)47parser.add_argument(48 "--type", help="Type of histogram (*bar*, barstacked, step, stepfilled)"49)50parser.add_argument("-o", "--output", help="Save image to the given filename.")51parser.add_argument(52 "--min",53 "--t-min",54 dest="value_min",55 type=float,56 help="Minimum metric value to display",57)58parser.add_argument(59 "--max",60 "--t-max",61 dest="value_max",62 type=float,63 help="Maximum metric value to display",64)65parser.add_argument(66 "--log-count",67 help="Use a logarithmic y-axis for the event count",68 action="store_true",69)2071args = parser.parse_args()72metric, [results] = load_results(parser, [args.file], args.metric)73metric_info = METRICS[metric]21def 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 )7275if args.labels:76 labels = args.labels.split(",")77else:78 labels = [b.get("name", b["command"]) for b in results]79all_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]7683value_min = (84 args.value_min85 if args.value_min is not None86 else np.min(list(map(np.min, all_values)))87)88value_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 ]8594bins = int(args.bins) if args.bins else "auto"95histtype = 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 )9697plt.figure(figsize=(10, 5))98plt.hist(99 all_values,100 label=labels,101 bins=bins,102 histtype=histtype,103 range=(value_min, value_max),104)105plt.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"99112plt.xlabel(metric_info.axis_label)113if 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 )114116if args.log_count:117 plt.yscale("log")118else:119 plt.ylim(0, None)115 plt.xlabel(metric_info.axis_label)116 if args.title:117 plt.title(args.title)118119 if args.log_count:120 plt.yscale("log")121 else:122 plt.ylim(0, None)123121if args.output:122 plt.savefig(args.output, dpi=600)123else:124 plt.show()124 if args.output:125 plt.savefig(args.output, dpi=600)126 else:127 plt.show()128129130if __name__ == "__main__":131 main()
modified:scripts/plot_parametrized.py+87 added-85 removed
15 unmodified lines
16import matplotlib.pyplot as plt1718from 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="+")23parser.add_argument(24 "--parameter-name",25 metavar="name",26 type=str,27 help="Deprecated; parameter names are now inferred from benchmark files",28)29parser.add_argument(30 "--log-x", help="Use a logarithmic x (parameter) axis", action="store_true"31)32parser.add_argument(33 "--log-y",34 "--log-time",35 dest="log_y",36 help="Use a logarithmic metric axis",37 action="store_true",38)39parser.add_argument(40 "--titles", help="Comma-separated list of titles for the plot legend"41)42parser.add_argument("-o", "--output", help="Save image to the given filename.")2044args = parser.parse_args()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"21def 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.")4546 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 )5454def 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)5859 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))7059def 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"]))8283 parameter_name = None8472def 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_name9293 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 ]9985parameter_name = None100 plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2)10187for 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)10495 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)109102 plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2)110 if args.log_x:111 plt.xscale("log")112104plt.xlabel(parameter_name)105plt.ylabel(metric_info.axis_label)113 if args.titles:114 plt.legend(args.titles.split(","))115107if args.log_y:108 plt.yscale("log")109else:110 plt.ylim(0, None)116 if args.output:117 plt.savefig(args.output)118 else:119 plt.show()120112if args.log_x:113 plt.xscale("log")121115if args.titles:116 plt.legend(args.titles.split(","))117118if args.output:119 plt.savefig(args.output)120else:121 plt.show()122if __name__ == "__main__":123 main()
modified:scripts/plot_progression.py+54 added-49 removed
27 unmodified lines
28 kernel = np.ones(num_runs) / num_runs29 return np.convolve(values_padded, kernel, mode="valid")303132def main():32parser = argparse.ArgumentParser(description=__doc__)33add_metric_argument(parser)34parser.add_argument("file", help="JSON file with benchmark results")35parser.add_argument("--title", help="Plot Title")36parser.add_argument("-o", "--output", help="Save image to the given filename.")37parser.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)44parser.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 )5051 args = parser.parse_args()52 metric, [results] = load_results(parser, [args.file], args.metric)53 metric_info = METRICS[metric]5451args = parser.parse_args()52metric, [results] = load_results(parser, [args.file], args.metric)53metric_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)6155for 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])6561 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 )7265 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, "-")7572 average = moving_average(values, moving_average_width)73 plt.plot(nums, average, "-")76 if args.title:77 plt.title(args.title)7875if 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)8578legend = []79for result in results:80 legend.append(result.get("name", result["command"]))81 if not args.no_moving_average:82 legend.append("moving average")83plt.legend(legend)86 plt.ylabel(metric_info.axis_label)8785plt.ylabel(metric_info.axis_label)88 if args.output:89 plt.savefig(args.output)90 else:91 plt.show()9287if args.output:88 plt.savefig(args.output)89else:90 plt.show()9394if __name__ == "__main__":95 main()
modified:scripts/plot_whisker.py+47 added-40 removed
19 unmodified lines
20import matplotlib.pyplot as plt2122from 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")27parser.add_argument("--title", help="Plot Title")28parser.add_argument("--sort-by", choices=["median"], help="Sort method")29parser.add_argument(30 "--labels", help="Comma-separated list of entries for the plot legend"31)32parser.add_argument("-o", "--output", help="Save image to the given filename.")2434args = parser.parse_args()35metric, [results] = load_results(parser, [args.file], args.metric)36metric_info = METRICS[metric]25def 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.")3538if args.labels:39 labels = args.labels.split(",")40else:41 labels = [b.get("name", b["command"]) for b in results]42values = [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]3946if 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 ]4852plt.figure(figsize=(10, 6), constrained_layout=True)53boxplot = plt.boxplot(values, vert=True, patch_artist=True)54cmap = plt.get_cmap("rainbow")55colors = [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]5457for 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))]5960 for patch, color in zip(boxplot["boxes"], colors):61 patch.set_facecolor(color)6260if args.title:61 plt.title(args.title)62plt.legend(handles=boxplot["boxes"], labels=labels, loc="best", fontsize="medium")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)68else: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()737475if __name__ == "__main__":76 main()
modified:scripts/README.md+23 added-13 removed
modified:scripts/welch_ttest.py+35 added-29 removed
14 unmodified lines
15from 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()1924metric, [results] = load_results(parser, [args.file], args.metric)20def 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()2526if len(results) != 2:27 parser.error("the input file must contain exactly two benchmarks")26 metric, [results] = load_results(parser, [args.file], args.metric)2729a, b = (x.get("name", x["command"]) 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")28 if len(results) != 2:29 parser.error("the input file must contain exactly two benchmarks")3034print(f"Metric: {METRICS[metric].label}")35print(f"Command 1: {a}")36print(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")3538t, 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()36 print(f"Metric: {METRICS[metric].label}")37 print(f"Command 1: {a}")38 print(f"Command 2: {b}\n")3940 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()4746if dispose:47 print(48 f"A statistically significant difference in mean value was detected (p < {th})."49 )50else: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 )565758if __name__ == "__main__":59 main()
added:pyproject.toml+36 added
1[project]2name = "hyperfine-scripts"3version = "0.1.0"4description = "Plot and analyze hyperfine JSON benchmark results"5requires-python = ">=3.10"6license-files = ["LICENSE-APACHE", "LICENSE-MIT"]7dependencies = [8 "matplotlib",9 "numpy",10 "pyqt6",11 "scipy",12]1314[project.scripts]15advanced_statistics = "advanced_statistics:main"16plot_benchmark_comparison = "plot_benchmark_comparison:main"17plot_histogram = "plot_histogram:main"18plot_parametrized = "plot_parametrized:main"19plot_progression = "plot_progression:main"20plot_whisker = "plot_whisker:main"21welch_ttest = "welch_ttest:main"2223[tool.uv.build-backend]24module-root = "scripts"25module-name = ""26namespace = true27source-exclude = [28 "/scripts/README.md",29 "/scripts/ruff.toml",30 "/scripts/.*",31 "*.egg-info",32]3334[build-system]35requires = ["uv_build>=0.12.23,<0.13"]36build-backend = "uv_build"
modified:README.md+10 added-1 removed
255 unmodified lines
256The 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 lot258of helpful Python programs to further analyze benchmark results and create helpful259visualizations, like a histogram of runtimes or a whisker plot to compare260multiple benchmarks:260multiple benchmarks.261262For example, these two commands create the following plots:263264```bash265uvx --from 'git+https://github.com/sharkdp/hyperfine' \266 plot_histogram results.json267uvx --from 'git+https://github.com/sharkdp/hyperfine' \268 plot_whisker results.json269```270271| ![](doc/histogram.png) | ![](doc/whisker.png) |272|---:|---:|273274
184 unmodified lines