Skip to content
Myr

plot_histogram.py

This file

Path

scripts/plot_histogram.py

131 lines · 3.3 KiB · Python

Last changed by

Make plotting scripts runnable with uvDavid Peterbefore adoptionce49529

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 argparse1415import matplotlib.pyplot as plt16import numpy as np1718from plot_utils import METRICS, add_metric_argument, load_results192021def main():22    parser = argparse.ArgumentParser(description=__doc__)23    add_metric_argument(parser)24    parser.add_argument("file", help="JSON file with benchmark results")25    parser.add_argument("--title", help="Plot title")26    parser.add_argument(27        "--labels", help="Comma-separated list of entries for the plot legend"28    )29    parser.add_argument("--bins", help="Number of bins (default: auto)")30    parser.add_argument(31        "--legend-location",32        help="Location of the legend on plot (default: upper center)",33        choices=[34            "upper center",35            "lower center",36            "right",37            "left",38            "best",39            "upper left",40            "upper right",41            "lower left",42            "lower right",43            "center left",44            "center right",45            "center",46        ],47        default="upper center",48    )49    parser.add_argument(50        "--type", help="Type of histogram (*bar*, barstacked, step, stepfilled)"51    )52    parser.add_argument("-o", "--output", help="Save image to the given filename.")53    parser.add_argument(54        "--min",55        "--t-min",56        dest="value_min",57        type=float,58        help="Minimum metric value to display",59    )60    parser.add_argument(61        "--max",62        "--t-max",63        dest="value_max",64        type=float,65        help="Maximum metric value to display",66    )67    parser.add_argument(68        "--log-count",69        help="Use a logarithmic y-axis for the event count",70        action="store_true",71    )7273    args = parser.parse_args()74    metric, [results] = load_results(parser, [args.file], args.metric)75    metric_info = METRICS[metric]7677    if args.labels:78        labels = args.labels.split(",")79    else:80        labels = [b.get("name", b["command"]) for b in results]81    all_values = [82        [m[metric]["value"] / metric_info.scale for m in b["measurements"]]83        for b in results84    ]8586    value_min = (87        args.value_min88        if args.value_min is not None89        else np.min(list(map(np.min, all_values)))90    )91    value_max = (92        args.value_max93        if args.value_max is not None94        else np.max(list(map(np.max, all_values)))95    )9697    bins = int(args.bins) if args.bins else "auto"98    histtype = args.type if args.type else "bar"99100    plt.figure(figsize=(10, 5))101    plt.hist(102        all_values,103        label=labels,104        bins=bins,105        histtype=histtype,106        range=(value_min, value_max),107    )108    plt.legend(109        loc=args.legend_location,110        fancybox=True,111        shadow=True,112        prop={"size": 10, "family": ["Source Code Pro", "Fira Mono", "Courier New"]},113    )114115    plt.xlabel(metric_info.axis_label)116    if args.title:117        plt.title(args.title)118119    if args.log_count:120        plt.yscale("log")121    else:122        plt.ylim(0, None)123124    if args.output:125        plt.savefig(args.output, dpi=600)126    else:127        plt.show()128129130if __name__ == "__main__":131    main()