Skip to content
Myr

plot_benchmark_comparison.py

This file

Path

scripts/plot_benchmark_comparison.py

83 lines · 2.1 KiB · Python

Last changed by

Address commentsMartin Liskabefore adoption3cedcc3

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 np2223parser = argparse.ArgumentParser(description=__doc__)24parser.add_argument(25    "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"26)27parser.add_argument("--title", help="Plot Title")28parser.add_argument(29    "--benchmark-names", nargs="+", help="Names of the benchmark groups"30)31parser.add_argument("-o", "--output", help="Save image to the given filename")3233args = parser.parse_args()3435commands = None36data = []37inputs = []3839if args.benchmark_names:40    assert len(args.files) == len(41        args.benchmark_names42    ), "Number of benchmark names must match the number of input files."4344for i, filename in enumerate(args.files):45    with open(filename) as f:46        results = json.load(f)["results"]47    benchmark_commands = [b["command"] for b in results]48    if commands is None:49        commands = benchmark_commands50    else:51        assert (52            commands == benchmark_commands53        ), f"Unexpected commands in {filename}: {benchmark_commands}, expected: {commands}"54    data.append([round(b["mean"], 2) for b in results])55    if args.benchmark_names:56        inputs.append(args.benchmark_names[i])57    else:58        inputs.append(filename.stem)5960data = np.transpose(data)61x = np.arange(len(inputs))  # the label locations62width = 0.25  # the width of the bars6364fig, ax = plt.subplots(layout="constrained")65fig.set_figheight(5)66fig.set_figwidth(10)67for i, command in enumerate(commands):68    offset = width * (i + 1)69    rects = ax.bar(x + offset, data[i], width, label=command)7071ax.set_xticks(x + 0.5, inputs)72ax.grid(visible=True, axis="y")7374if args.title:75    plt.title(args.title)76plt.xlabel("Benchmark")77plt.ylabel("Time [s]")78plt.legend(title="Command")7980if args.output:81    plt.savefig(args.output)82else:83    plt.show()