Skip to content
Myr

plot_histogram.py

This file

Path

scripts/plot_histogram.py

104 lines · 2.5 KiB · Python

Last changed by

Add PEP-723 inline metadataDavid Peterbefore adoptioncfae9cb

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"""This program shows `hyperfine` benchmark results as a histogram."""1213import argparse14import json15import numpy as np16import matplotlib.pyplot as plt1718parser = argparse.ArgumentParser(description=__doc__)19parser.add_argument("file", help="JSON file with benchmark results")20parser.add_argument("--title", help="Plot title")21parser.add_argument(22    "--labels", help="Comma-separated list of entries for the plot legend"23)24parser.add_argument("--bins", help="Number of bins (default: auto)")25parser.add_argument(26    "--legend-location",27    help="Location of the legend on plot (default: upper center)",28    choices=[29        "upper center",30        "lower center",31        "right",32        "left",33        "best",34        "upper left",35        "upper right",36        "lower left",37        "lower right",38        "center left",39        "center right",40        "center",41    ],42    default="upper center",43)44parser.add_argument(45    "--type", help="Type of histogram (*bar*, barstacked, step, stepfilled)"46)47parser.add_argument("-o", "--output", help="Save image to the given filename.")48parser.add_argument(49    "--t-min", metavar="T", help="Minimum time to be displayed (seconds)"50)51parser.add_argument(52    "--t-max", metavar="T", help="Maximum time to be displayed (seconds)"53)54parser.add_argument(55    "--log-count",56    help="Use a logarithmic y-axis for the event count",57    action="store_true",58)5960args = parser.parse_args()6162with open(args.file) as f:63    results = json.load(f)["results"]6465if args.labels:66    labels = args.labels.split(",")67else:68    labels = [b["command"] for b in results]69all_times = [b["times"] for b in results]7071t_min = float(args.t_min) if args.t_min else np.min(list(map(np.min, all_times)))72t_max = float(args.t_max) if args.t_max else np.max(list(map(np.max, all_times)))7374bins = int(args.bins) if args.bins else "auto"75histtype = args.type if args.type else "bar"7677plt.figure(figsize=(10, 5))78plt.hist(79    all_times,80    label=labels,81    bins=bins,82    histtype=histtype,83    range=(t_min, t_max),84)85plt.legend(86    loc=args.legend_location,87    fancybox=True,88    shadow=True,89    prop={"size": 10, "family": ["Source Code Pro", "Fira Mono", "Courier New"]},90)9192plt.xlabel("Time [s]")93if args.title:94    plt.title(args.title)9596if args.log_count:97    plt.yscale("log")98else:99    plt.ylim(0, None)100101if args.output:102    plt.savefig(args.output, dpi=600)103else:104    plt.show()