Skip to content
Myr

plot_parametrized.py

This file

Path

scripts/plot_parametrized.py

121 lines · 3.3 KiB · Python

Last changed by

Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9

History of this file

Take 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_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.")4344args = 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"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 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_name9495    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    ]101102    plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2)103104plt.xlabel(parameter_name)105plt.ylabel(metric_info.axis_label)106107if args.log_y:108    plt.yscale("log")109else:110    plt.ylim(0, None)111112if args.log_x:113    plt.xscale("log")114115if args.titles:116    plt.legend(args.titles.split(","))117118if args.output:119    plt.savefig(args.output)120else:121    plt.show()