Skip to content
Myr

plot_benchmark_comparison.py

This file

Path

scripts/plot_benchmark_comparison.py

91 lines · 2.6 KiB · Python

Last changed by

Make plotting scripts runnable with uvDavid Peterbefore adoptionce49529

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_results232425def main():26    parser = argparse.ArgumentParser(description=__doc__)27    add_metric_argument(parser)28    parser.add_argument(29        "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"30    )31    parser.add_argument("--title", help="Plot Title")32    parser.add_argument(33        "--benchmark-names", nargs="+", help="Names of the benchmark groups"34    )35    parser.add_argument("-o", "--output", help="Save image to the given filename")3637    args = parser.parse_args()38    metric, datasets = load_results(parser, args.files, args.metric)39    metric_info = METRICS[metric]4041    commands = None42    data = []43    inputs = []4445    if args.benchmark_names:46        assert len(args.files) == len(args.benchmark_names), (47            "Number of benchmark names must match the number of input files."48        )4950    for i, (filename, results) in enumerate(zip(args.files, datasets)):51        benchmark_commands = [b.get("name", b["command"]) for b in results]52        if commands is None:53            commands = benchmark_commands54        else:55            assert commands == benchmark_commands, (56                f"Unexpected commands in {filename}: {benchmark_commands}, expected: {commands}"57            )58        data.append([b["summary"][metric]["mean"] / metric_info.scale for b in results])59        if args.benchmark_names:60            inputs.append(args.benchmark_names[i])61        else:62            inputs.append(filename.stem)6364    data = np.transpose(data)65    x = np.arange(len(inputs))  # the label locations66    width = 0.25  # the width of the bars6768    fig, ax = plt.subplots(layout="constrained")69    fig.set_figheight(5)70    fig.set_figwidth(10)71    for i, command in enumerate(commands):72        offset = width * (i + 1)73        ax.bar(x + offset, data[i], width, label=command)7475    ax.set_xticks(x + 0.5, inputs)76    ax.grid(visible=True, axis="y")7778    if args.title:79        plt.title(args.title)80    plt.xlabel("Benchmark")81    plt.ylabel(metric_info.axis_label)82    plt.legend(title="Command")8384    if args.output:85        plt.savefig(args.output)86    else:87        plt.show()888990if __name__ == "__main__":91    main()