Skip to content
Myr

plot_parametrized.py

This file

Path

scripts/plot_parametrized.py

111 lines · 3.0 KiB · Python

Last changed by

Add PEP-723 inline metadataDavid Peterbefore adoptioncfae9cb

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 json15import matplotlib.pyplot as plt16import sys1718parser = argparse.ArgumentParser(description=__doc__)19parser.add_argument("file", help="JSON file with benchmark results", nargs="+")20parser.add_argument(21    "--parameter-name",22    metavar="name",23    type=str,24    help="Deprecated; parameter names are now inferred from benchmark files",25)26parser.add_argument(27    "--log-x", help="Use a logarithmic x (parameter) axis", action="store_true"28)29parser.add_argument(30    "--log-time", help="Use a logarithmic time axis", action="store_true"31)32parser.add_argument(33    "--titles", help="Comma-separated list of titles for the plot legend"34)35parser.add_argument("-o", "--output", help="Save image to the given filename.")3637args = parser.parse_args()38if args.parameter_name is not None:39    sys.stderr.write(40        "warning: --parameter-name is deprecated; names are inferred from "41        "benchmark results\n"42    )434445def die(msg):46    sys.stderr.write(f"fatal: {msg}\n")47    sys.exit(1)484950def extract_parameters(results):51    """Return `(parameter_name: str, parameter_values: List[float])`."""52    if not results:53        die("no benchmark data to plot")54    (names, values) = zip(*(unique_parameter(b) for b in results))55    names = frozenset(names)56    if len(names) != 1:57        die(58            f"benchmarks must all have the same parameter name, but found: {sorted(names)}"59        )60    return (next(iter(names)), list(values))616263def unique_parameter(benchmark):64    """Return the unique parameter `(name: str, value: float)`, or die."""65    params_dict = benchmark.get("parameters", {})66    if not params_dict:67        die("benchmarks must have exactly one parameter, but found none")68    if len(params_dict) > 1:69        die(70            f"benchmarks must have exactly one parameter, but found multiple: {sorted(params_dict)}"71        )72    [(name, value)] = params_dict.items()73    return (name, float(value))747576parameter_name = None7778for filename in args.file:79    with open(filename) as f:80        results = json.load(f)["results"]8182    (this_parameter_name, parameter_values) = extract_parameters(results)83    if parameter_name is not None and this_parameter_name != parameter_name:84        die(85            f"files must all have the same parameter name, but found {parameter_name!r} vs. {this_parameter_name!r}"86        )87    parameter_name = this_parameter_name8889    times_mean = [b["mean"] for b in results]90    times_stddev = [b["stddev"] for b in results]9192    plt.errorbar(x=parameter_values, y=times_mean, yerr=times_stddev, capsize=2)9394plt.xlabel(parameter_name)95plt.ylabel("Time [s]")9697if args.log_time:98    plt.yscale("log")99else:100    plt.ylim(0, None)101102if args.log_x:103    plt.xscale("log")104105if args.titles:106    plt.legend(args.titles.split(","))107108if args.output:109    plt.savefig(args.output)110else:111    plt.show()