Skip to content
Myr

plot_parametrized.py

This file

Path

scripts/plot_parametrized.py

115 lines · 3.1 KiB · Python

Last changed by

Export metric summaries and adapt analysis scriptsDavid Peterbefore adoption1b3ec92

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 sys1617import matplotlib.pyplot as plt1819parser = argparse.ArgumentParser(description=__doc__)20parser.add_argument("file", help="JSON file with benchmark results", nargs="+")21parser.add_argument(22    "--parameter-name",23    metavar="name",24    type=str,25    help="Deprecated; parameter names are now inferred from benchmark files",26)27parser.add_argument(28    "--log-x", help="Use a logarithmic x (parameter) axis", action="store_true"29)30parser.add_argument(31    "--log-time", help="Use a logarithmic time axis", action="store_true"32)33parser.add_argument(34    "--titles", help="Comma-separated list of titles for the plot legend"35)36parser.add_argument("-o", "--output", help="Save image to the given filename.")3738args = parser.parse_args()39if args.parameter_name is not None:40    sys.stderr.write(41        "warning: --parameter-name is deprecated; names are inferred from "42        "benchmark results\n"43    )444546def die(msg):47    sys.stderr.write(f"fatal: {msg}\n")48    sys.exit(1)495051def extract_parameters(results):52    """Return `(parameter_name: str, parameter_values: List[float])`."""53    if not results:54        die("no benchmark data to plot")55    (names, values) = zip(*(unique_parameter(b) for b in results))56    names = frozenset(names)57    if len(names) != 1:58        die(59            f"benchmarks must all have the same parameter name, but found: {sorted(names)}"60        )61    return (next(iter(names)), list(values))626364def unique_parameter(benchmark):65    """Return the unique parameter `(name: str, value: float)`, or die."""66    params_dict = benchmark.get("parameters", {})67    if not params_dict:68        die("benchmarks must have exactly one parameter, but found none")69    if len(params_dict) > 1:70        die(71            f"benchmarks must have exactly one parameter, but found multiple: {sorted(params_dict)}"72        )73    [(name, value)] = params_dict.items()74    return (name, float(value["value"]))757677parameter_name = None7879for filename in args.file:80    with open(filename) as f:81        results = json.load(f)["results"]8283    (this_parameter_name, parameter_values) = extract_parameters(results)84    if parameter_name is not None and this_parameter_name != parameter_name:85        die(86            f"files must all have the same parameter name, but found {parameter_name!r} vs. {this_parameter_name!r}"87        )88    parameter_name = this_parameter_name8990    summaries = [b["summary"]["time_wall_clock"] for b in results]91    times_mean = [s["mean"] for s in summaries]92    times_stddev = [93        s["stddev"] if s["stddev"] is not None else float("nan") for s in summaries94    ]9596    plt.errorbar(x=parameter_values, y=times_mean, yerr=times_stddev, capsize=2)9798plt.xlabel(parameter_name)99plt.ylabel("Time [s]")100101if args.log_time:102    plt.yscale("log")103else:104    plt.ylim(0, None)105106if args.log_x:107    plt.xscale("log")108109if args.titles:110    plt.legend(args.titles.split(","))111112if args.output:113    plt.savefig(args.output)114else:115    plt.show()