Skip to content
Myr

plot_benchmark_comparison.py

This file

Path

scripts/plot_benchmark_comparison.py

88 lines · 2.4 KiB · Python

Last changed by

Support all exported metrics in plotting scripts (#981)David Peterbefore adoptionef86c83

History of this file

Take it

1#!/usr/bin/env python2# /// script3# requires-python = ">=3.10"4# dependencies = [5#     "matplotlib",6#     "pyqt6",7#     "numpy",8# ]9# ///1011"""12This script shows `hyperfine` benchmark results as a bar plot grouped by command.13Note all the input files must contain results for all commands.14"""1516import argparse17import json18import pathlib1920import matplotlib.pyplot as plt21import numpy as np2223from plot_utils import METRICS, add_metric_argument, validate_metric2425parser = argparse.ArgumentParser(description=__doc__)26add_metric_argument(parser)27parser.add_argument(28    "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"29)30parser.add_argument("--title", help="Plot Title")31parser.add_argument(32    "--benchmark-names", nargs="+", help="Names of the benchmark groups"33)34parser.add_argument("-o", "--output", help="Save image to the given filename")3536args = parser.parse_args()37metric_label, metric_scale = METRICS[args.metric]3839commands = None40data = []41inputs = []4243if args.benchmark_names:44    assert len(args.files) == len(args.benchmark_names), (45        "Number of benchmark names must match the number of input files."46    )4748for i, filename in enumerate(args.files):49    with open(filename) as f:50        results = json.load(f)["results"]51    validate_metric(parser, results, args.metric)52    benchmark_commands = [b.get("name", b["command"]) for b in results]53    if commands is None:54        commands = benchmark_commands55    else:56        assert commands == benchmark_commands, (57            f"Unexpected commands in {filename}: {benchmark_commands}, expected: {commands}"58        )59    data.append([b["summary"][args.metric]["mean"] / metric_scale for b in results])60    if args.benchmark_names:61        inputs.append(args.benchmark_names[i])62    else:63        inputs.append(filename.stem)6465data = np.transpose(data)66x = np.arange(len(inputs))  # the label locations67width = 0.25  # the width of the bars6869fig, ax = plt.subplots(layout="constrained")70fig.set_figheight(5)71fig.set_figwidth(10)72for i, command in enumerate(commands):73    offset = width * (i + 1)74    rects = ax.bar(x + offset, data[i], width, label=command)7576ax.set_xticks(x + 0.5, inputs)77ax.grid(visible=True, axis="y")7879if args.title:80    plt.title(args.title)81plt.xlabel("Benchmark")82plt.ylabel(metric_label)83plt.legend(title="Command")8485if args.output:86    plt.savefig(args.output)87else:88    plt.show()