Skip to content
Myr

plot_benchmark_comparison.py

This file

Path

scripts/plot_benchmark_comparison.py

85 lines · 2.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#     "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 pathlib1819import matplotlib.pyplot as plt20import numpy as np2122from plot_utils import METRICS, add_metric_argument, load_results2324parser = argparse.ArgumentParser(description=__doc__)25add_metric_argument(parser)26parser.add_argument(27    "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"28)29parser.add_argument("--title", help="Plot Title")30parser.add_argument(31    "--benchmark-names", nargs="+", help="Names of the benchmark groups"32)33parser.add_argument("-o", "--output", help="Save image to the given filename")3435args = parser.parse_args()36metric, datasets = load_results(parser, args.files, args.metric)37metric_info = METRICS[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, results) in enumerate(zip(args.files, datasets)):49    benchmark_commands = [b.get("name", b["command"]) for b in results]50    if commands is None:51        commands = benchmark_commands52    else:53        assert commands == benchmark_commands, (54            f"Unexpected commands in {filename}: {benchmark_commands}, expected: {commands}"55        )56    data.append([b["summary"][metric]["mean"] / metric_info.scale for b in results])57    if args.benchmark_names:58        inputs.append(args.benchmark_names[i])59    else:60        inputs.append(filename.stem)6162data = np.transpose(data)63x = np.arange(len(inputs))  # the label locations64width = 0.25  # the width of the bars6566fig, ax = plt.subplots(layout="constrained")67fig.set_figheight(5)68fig.set_figwidth(10)69for i, command in enumerate(commands):70    offset = width * (i + 1)71    rects = ax.bar(x + offset, data[i], width, label=command)7273ax.set_xticks(x + 0.5, inputs)74ax.grid(visible=True, axis="y")7576if args.title:77    plt.title(args.title)78plt.xlabel("Benchmark")79plt.ylabel(metric_info.axis_label)80plt.legend(title="Command")8182if args.output:83    plt.savefig(args.output)84else:85    plt.show()