plot_parametrized.py
This file
Path
scripts/plot_parametrized.py
123 lines · 3.7 KiB · Python
Last changed by
Make plotting scripts runnable with uvDavid Peterbefore adoptionce49529
History of this fileTake it
1#!/usr/bin/env python2# /// script3# requires-python = ">=3.10"4# dependencies = [5# "matplotlib",6# "pyqt6",7# ]8# ///910"""This program shows parametrized `hyperfine` benchmark results as an11errorbar plot."""1213import argparse14import sys1516import matplotlib.pyplot as plt1718from plot_utils import METRICS, add_metric_argument, load_results192021def 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 )5455 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))7071 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 = None8485 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 ]99100 plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2)101102 plt.xlabel(parameter_name)103 plt.ylabel(metric_info.axis_label)104105 if args.log_y:106 plt.yscale("log")107 else:108 plt.ylim(0, None)109110 if args.log_x:111 plt.xscale("log")112113 if args.titles:114 plt.legend(args.titles.split(","))115116 if args.output:117 plt.savefig(args.output)118 else:119 plt.show()120121122if __name__ == "__main__":123 main()