Skip to content
Myr

plot_whisker.py

This file

Path

scripts/plot_whisker.py

58 lines · 1.9 KiB · Python

Last changed by

Update formatting, use f-stringsDavid Peterbefore adoption65dd84f

History of this file

Take it

1#!/usr/bin/env python23"""This program shows `hyperfine` benchmark results as a box and whisker plot.45Quoting from the matplotlib documentation:6    The box extends from the lower to upper quartile values of the data, with7    a line at the median. The whiskers extend from the box to show the range8    of the data. Flier points are those past the end of the whiskers.9"""1011import argparse12import json13import matplotlib.pyplot as plt1415parser = argparse.ArgumentParser(description=__doc__)16parser.add_argument("file", help="JSON file with benchmark results")17parser.add_argument("--title", help="Plot Title")18parser.add_argument("--sort-by", choices=["median"], help="Sort method")19parser.add_argument(20    "--labels", help="Comma-separated list of entries for the plot legend"21)22parser.add_argument("-o", "--output", help="Save image to the given filename.")2324args = parser.parse_args()2526with open(args.file, encoding="utf-8") as f:27    results = json.load(f)["results"]2829if args.labels:30    labels = args.labels.split(",")31else:32    labels = [b["command"] for b in results]33times = [b["times"] for b in results]3435if args.sort_by == "median":36    medians = [b["median"] for b in results]37    indices = sorted(range(len(labels)), key=lambda k: medians[k])38    labels = [labels[i] for i in indices]39    times = [times[i] for i in indices]4041plt.figure(figsize=(10, 6), constrained_layout=True)42boxplot = plt.boxplot(times, vert=True, patch_artist=True)43cmap = plt.get_cmap("rainbow")44colors = [cmap(val / len(times)) for val in range(len(times))]4546for patch, color in zip(boxplot["boxes"], colors):47    patch.set_facecolor(color)4849if args.title:50    plt.title(args.title)51plt.legend(handles=boxplot["boxes"], labels=labels, loc="best", fontsize="medium")52plt.ylabel("Time [s]")53plt.ylim(0, None)54plt.xticks(list(range(1, len(labels) + 1)), labels, rotation=45)55if args.output:56    plt.savefig(args.output)57else:58    plt.show()