plot_parametrized.py
This file
Path
scripts/plot_parametrized.py
125 lines · 3.4 KiB · Python
Last changed by
Support all exported metrics in plotting scripts (#981)David Peterbefore adoptionef86c83
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 json15import sys1617import matplotlib.pyplot as plt1819from plot_utils import METRICS, add_metric_argument, validate_metric2021parser = argparse.ArgumentParser(description=__doc__)22add_metric_argument(parser)23parser.add_argument("file", help="JSON file with benchmark results", nargs="+")24parser.add_argument(25 "--parameter-name",26 metavar="name",27 type=str,28 help="Deprecated; parameter names are now inferred from benchmark files",29)30parser.add_argument(31 "--log-x", help="Use a logarithmic x (parameter) axis", action="store_true"32)33parser.add_argument(34 "--log-y",35 "--log-time",36 dest="log_y",37 help="Use a logarithmic metric axis",38 action="store_true",39)40parser.add_argument(41 "--titles", help="Comma-separated list of titles for the plot legend"42)43parser.add_argument("-o", "--output", help="Save image to the given filename.")4445args = parser.parse_args()46metric_label, metric_scale = METRICS[args.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"51 )525354def die(msg):55 sys.stderr.write(f"fatal: {msg}\n")56 sys.exit(1)575859def 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))707172def 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"]))838485parameter_name = None8687for filename in args.file:88 with open(filename) as f:89 results = json.load(f)["results"]90 validate_metric(parser, results, args.metric)9192 (this_parameter_name, parameter_values) = extract_parameters(results)93 if parameter_name is not None and this_parameter_name != parameter_name:94 die(95 f"files must all have the same parameter name, but found {parameter_name!r} vs. {this_parameter_name!r}"96 )97 parameter_name = this_parameter_name9899 summaries = [b["summary"][args.metric] for b in results]100 means = [s["mean"] / metric_scale for s in summaries]101 stddevs = [102 s["stddev"] / metric_scale if s["stddev"] is not None else float("nan")103 for s in summaries104 ]105106 plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2)107108plt.xlabel(parameter_name)109plt.ylabel(metric_label)110111if args.log_y:112 plt.yscale("log")113else:114 plt.ylim(0, None)115116if args.log_x:117 plt.xscale("log")118119if args.titles:120 plt.legend(args.titles.split(","))121122if args.output:123 plt.savefig(args.output)124else:125 plt.show()