Skip to content
Myr

plot_histogram.py

This file

Path

scripts/plot_histogram.py

96 lines · 2.4 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 histogram."""45import argparse6import json7import numpy as np8import matplotlib.pyplot as plt910parser = argparse.ArgumentParser(description=__doc__)11parser.add_argument("file", help="JSON file with benchmark results")12parser.add_argument("--title", help="Plot title")13parser.add_argument(14    "--labels", help="Comma-separated list of entries for the plot legend"15)16parser.add_argument("--bins", help="Number of bins (default: auto)")17parser.add_argument(18    "--legend-location",19    help="Location of the legend on plot (default: upper center)",20    choices=[21        "upper center",22        "lower center",23        "right",24        "left",25        "best",26        "upper left",27        "upper right",28        "lower left",29        "lower right",30        "center left",31        "center right",32        "center",33    ],34    default="upper center",35)36parser.add_argument(37    "--type", help="Type of histogram (*bar*, barstacked, step, stepfilled)"38)39parser.add_argument("-o", "--output", help="Save image to the given filename.")40parser.add_argument(41    "--t-min", metavar="T", help="Minimum time to be displayed (seconds)"42)43parser.add_argument(44    "--t-max", metavar="T", help="Maximum time to be displayed (seconds)"45)46parser.add_argument(47    "--log-count",48    help="Use a logarithmic y-axis for the event count",49    action="store_true",50)5152args = parser.parse_args()5354with open(args.file) as f:55    results = json.load(f)["results"]5657if args.labels:58    labels = args.labels.split(",")59else:60    labels = [b["command"] for b in results]61all_times = [b["times"] for b in results]6263t_min = float(args.t_min) if args.t_min else np.min(list(map(np.min, all_times)))64t_max = float(args.t_max) if args.t_max else np.max(list(map(np.max, all_times)))6566bins = int(args.bins) if args.bins else "auto"67histtype = args.type if args.type else "bar"6869plt.figure(figsize=(10, 5))70plt.hist(71    all_times,72    label=labels,73    bins=bins,74    histtype=histtype,75    range=(t_min, t_max),76)77plt.legend(78    loc=args.legend_location,79    fancybox=True,80    shadow=True,81    prop={"size": 10, "family": ["Source Code Pro", "Fira Mono", "Courier New"]},82)8384plt.xlabel("Time [s]")85if args.title:86    plt.title(args.title)8788if args.log_count:89    plt.yscale("log")90else:91    plt.ylim(0, None)9293if args.output:94    plt.savefig(args.output, dpi=600)95else:96    plt.show()