Skip to content
Myr

plot_parametrized.py

This file

Path

scripts/plot_parametrized.py

107 lines · 2.9 KiB · Python

Last changed by

Add parameters to plotting scriptsBenjamin Rosemannbefore adoptionb04a9ec

History of this file

Take it

1#!/usr/bin/env python23"""This program shows parametrized `hyperfine` benchmark results as an4errorbar plot."""56import argparse7import json8import matplotlib.pyplot as plt9import sys1011parser = argparse.ArgumentParser(description=__doc__)12parser.add_argument("file", help="JSON file with benchmark results", nargs="+")13parser.add_argument(14    "--parameter-name",15    metavar="name",16    type=str,17    help="Deprecated; parameter names are now inferred from benchmark files",18)19parser.add_argument(20    "--log-x", help="Use a logarithmic x (parameter) axis", action="store_true"21)22parser.add_argument(23    "--log-time", help="Use a logarithmic time axis", action="store_true"24)25parser.add_argument(26    "--titles", help="Comma-separated list of titles for the plot legend"27)28parser.add_argument("--imgname", help="Save image to the given filename.")2930args = parser.parse_args()31if args.parameter_name is not None:32    sys.stderr.write(33        "warning: --parameter-name is deprecated; names are inferred from "34        "benchmark results\n"35    )363738def die(msg):39    sys.stderr.write("fatal: %s\n" % (msg,))40    sys.exit(1)414243def extract_parameters(results):44    """Return `(parameter_name: str, parameter_values: List[float])`."""45    if not results:46        die("no benchmark data to plot")47    (names, values) = zip(*(unique_parameter(b) for b in results))48    names = frozenset(names)49    if len(names) != 1:50        die(51            "benchmarks must all have the same parameter name, but found: %s"52            % sorted(names)53        )54    return (next(iter(names)), list(values))555657def unique_parameter(benchmark):58    """Return the unique parameter `(name: str, value: float)`, or die."""59    params_dict = benchmark.get("parameters", {})60    if not params_dict:61        die("benchmarks must have exactly one parameter, but found none")62    if len(params_dict) > 1:63        die(64            "benchmarks must have exactly one parameter, but found multiple: %s"65            % sorted(params_dict)66        )67    [(name, value)] = params_dict.items()68    return (name, float(value))697071parameter_name = None7273for filename in args.file:74    with open(filename) as f:75        results = json.load(f)["results"]7677    (this_parameter_name, parameter_values) = extract_parameters(results)78    if parameter_name is not None and this_parameter_name != parameter_name:79        die(80            "files must all have the same parameter name, but found %r vs. %r"81            % (parameter_name, this_parameter_name)82        )83    parameter_name = this_parameter_name8485    times_mean = [b["mean"] for b in results]86    times_stddev = [b["stddev"] for b in results]8788    plt.errorbar(x=parameter_values, y=times_mean, yerr=times_stddev, capsize=2)8990plt.xlabel(parameter_name)91plt.ylabel("Time [s]")9293if args.log_time:94    plt.yscale("log")95else:96    plt.ylim(0, None)9798if args.log_x:99    plt.xscale("log")100101if args.titles:102    plt.legend(args.titles.split(","))103104if args.imgname:105    plt.savefig(args.imgname)106else:107    plt.show()