plot_benchmarks.py
This file
Path
scripts/plot_benchmarks.py
80 lines · 2.0 KiB · Python
Last changed by
Add plot_benchmarks scriptsMartin Liskabefore adoptionee4e4d0
History of this fileTake it
1#!/usr/bin/env python2# /// script3# requires-python = ">=3.10"4# dependencies = [5# "matplotlib",6# "pyqt6",7# "numpy",8# ]9# ///1011# This program shows `hyperfine` benchmark results as a bar plot grouped by command.1213import argparse14import json15import pathlib1617import matplotlib.pyplot as plt18import numpy as np1920parser = argparse.ArgumentParser(description=__doc__)21parser.add_argument(22 "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"23)24parser.add_argument("--title", help="Plot Title")25parser.add_argument(26 "--benchmark-names", nargs="+", help="Names of the benchmark groups"27)28parser.add_argument("-o", "--output", help="Save image to the given filename")2930args = parser.parse_args()3132commands = None33data = []34inputs = []3536if args.benchmark_names:37 assert len(args.files) == len(38 args.benchmark_names39 ), "Number of benchmark names must match the number of input files."4041for i, filename in enumerate(args.files):42 with open(filename) as f:43 results = json.load(f)["results"]44 benchmark_commands = [b["command"] for b in results]45 if commands is None:46 commands = benchmark_commands47 else:48 assert (49 commands == benchmark_commands50 ), f"Unexpected commands in {filename}: {benchmark_commands}, expected: {commands}"51 data.append([round(b["mean"], 2) for b in results])52 if args.benchmark_names:53 inputs.append(args.benchmark_names[i])54 else:55 inputs.append(filename.stem)5657data = np.transpose(data)58x = np.arange(len(inputs)) # the label locations59width = 0.25 # the width of the bars6061fig, ax = plt.subplots(layout="constrained")62fig.set_figheight(5)63fig.set_figwidth(10)64for i, command in enumerate(commands):65 offset = width * (i + 1)66 rects = ax.bar(x + offset, data[i], width, label=command)6768ax.set_xticks(x + 0.5, inputs)69ax.grid(visible=True, axis="y")7071if args.title:72 plt.title(args.title)73plt.xlabel("Benchmark")74plt.ylabel("Time [s]")75plt.legend(title="Command")7677if args.output:78 plt.savefig(args.output)79else:80 plt.show()