Skip to content
Myr

Support all exported metrics in plotting scripts (#981)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Peter · committed by GitHub · parent f26c015 · Browse files · 6 files+115 added−40 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+115 added−40 removed

  • other:+115 added−40 removed

6 files+115 added−40 removed

modified:scripts/plot_benchmark_comparison.py+13 added-8 removed
18 unmodified lines
1920import matplotlib.pyplot as plt21import numpy as np2223from plot_utils import METRICS, add_metric_argument, validate_metric2425parser = argparse.ArgumentParser(description=__doc__)26add_metric_argument(parser)27parser.add_argument(28 "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"29)30parser.add_argument("--title", help="Plot Title")
2 unmodified lines
33)34parser.add_argument("-o", "--output", help="Save image to the given filename")3536args = parser.parse_args()37metric_label, metric_scale = METRICS[args.metric]3839commands = None40data = []41inputs = []4243if args.benchmark_names:40 assert len(args.files) == len(41 args.benchmark_names42 ), "Number of benchmark names must match the number of input files."44 assert len(args.files) == len(args.benchmark_names), (45 "Number of benchmark names must match the number of input files."46 )4748for i, filename in enumerate(args.files):49 with open(filename) as f:50 results = json.load(f)["results"]51 validate_metric(parser, results, args.metric)52 benchmark_commands = [b.get("name", b["command"]) for b in results]53 if commands is None:54 commands = benchmark_commands55 else:51 assert (52 commands == benchmark_commands53 ), f"Unexpected commands in {filename}: {benchmark_commands}, expected: {commands}"54 data.append([b["summary"]["time_wall_clock"]["mean"] for b in results])56 assert commands == benchmark_commands, (57 f"Unexpected commands in {filename}: {benchmark_commands}, expected: {commands}"58 )59 data.append([b["summary"][args.metric]["mean"] / metric_scale for b in results])60 if args.benchmark_names:61 inputs.append(args.benchmark_names[i])62 else:63 inputs.append(filename.stem)
14 unmodified lines
7879if args.title:80 plt.title(args.title)81plt.xlabel("Benchmark")77plt.ylabel("Time [s]")82plt.ylabel(metric_label)83plt.legend(title="Command")8485if args.output:86 plt.savefig(args.output)
2 unmodified lines
modified:scripts/plot_histogram.py+30 added-9 removed
14 unmodified lines
1516import matplotlib.pyplot as plt17import numpy as np1819from plot_utils import METRICS, add_metric_argument, validate_metric2021parser = argparse.ArgumentParser(description=__doc__)22add_metric_argument(parser)23parser.add_argument("file", help="JSON file with benchmark results")24parser.add_argument("--title", help="Plot title")25parser.add_argument(26 "--labels", help="Comma-separated list of entries for the plot legend"
22 unmodified lines
49 "--type", help="Type of histogram (*bar*, barstacked, step, stepfilled)"50)51parser.add_argument("-o", "--output", help="Save image to the given filename.")52parser.add_argument(50 "--t-min", metavar="T", help="Minimum time to be displayed (seconds)"53 "--min",54 "--t-min",55 dest="value_min",56 type=float,57 help="Minimum value to display (seconds, or MiB for memory)",58)59parser.add_argument(53 "--t-max", metavar="T", help="Maximum time to be displayed (seconds)"60 "--max",61 "--t-max",62 dest="value_max",63 type=float,64 help="Maximum value to display (seconds, or MiB for memory)",65)66parser.add_argument(67 "--log-count",68 help="Use a logarithmic y-axis for the event count",69 action="store_true",70)7172args = parser.parse_args()73metric_label, metric_scale = METRICS[args.metric]7475with open(args.file) as f:76 results = json.load(f)["results"]77validate_metric(parser, results, args.metric)7879if args.labels:80 labels = args.labels.split(",")81else:82 labels = [b.get("name", b["command"]) for b in results]70all_times = [71 [m["time_wall_clock"]["value"] for m in b["measurements"]] for b in results83all_values = [84 [m[args.metric]["value"] / metric_scale for m in b["measurements"]] for b in results85]8674t_min = float(args.t_min) if args.t_min else np.min(list(map(np.min, all_times)))75t_max = float(args.t_max) if args.t_max else np.max(list(map(np.max, all_times)))87value_min = (88 args.value_min89 if args.value_min is not None90 else np.min(list(map(np.min, all_values)))91)92value_max = (93 args.value_max94 if args.value_max is not None95 else np.max(list(map(np.max, all_values)))96)9798bins = int(args.bins) if args.bins else "auto"99histtype = args.type if args.type else "bar"100101plt.figure(figsize=(10, 5))102plt.hist(82 all_times,103 all_values,104 label=labels,105 bins=bins,106 histtype=histtype,86 range=(t_min, t_max),107 range=(value_min, value_max),108)109plt.legend(110 loc=args.legend_location,111 fancybox=True,112 shadow=True,113 prop={"size": 10, "family": ["Source Code Pro", "Fira Mono", "Courier New"]},114)11595plt.xlabel("Time [s]")116plt.xlabel(metric_label)117if args.title:118 plt.title(args.title)119120if args.log_count:
8 unmodified lines
modified:scripts/plot_parametrized.py+18 added-8 removed
14 unmodified lines
15import sys1617import matplotlib.pyplot as plt1819from plot_utils import METRICS, add_metric_argument, validate_metric2021parser = argparse.ArgumentParser(description=__doc__)22add_metric_argument(parser)23parser.add_argument("file", help="JSON file with benchmark results", nargs="+")24parser.add_argument(25 "--parameter-name",26 metavar="name",
3 unmodified lines
30parser.add_argument(31 "--log-x", help="Use a logarithmic x (parameter) axis", action="store_true"32)33parser.add_argument(31 "--log-time", help="Use a logarithmic time axis", action="store_true"34 "--log-y",35 "--log-time",36 dest="log_y",37 help="Use a logarithmic metric axis",38 action="store_true",39)40parser.add_argument(41 "--titles", help="Comma-separated list of titles for the plot legend"42)43parser.add_argument("-o", "--output", help="Save image to the given filename.")4445args = parser.parse_args()46metric_label, metric_scale = METRICS[args.metric]47if args.parameter_name is not None:48 sys.stderr.write(49 "warning: --parameter-name is deprecated; names are inferred from "50 "benchmark results\n"
35 unmodified lines
8687for filename in args.file:88 with open(filename) as f:89 results = json.load(f)["results"]90 validate_metric(parser, results, args.metric)9192 (this_parameter_name, parameter_values) = extract_parameters(results)93 if parameter_name is not None and this_parameter_name != parameter_name:94 die(95 f"files must all have the same parameter name, but found {parameter_name!r} vs. {this_parameter_name!r}"96 )97 parameter_name = this_parameter_name9890 summaries = [b["summary"]["time_wall_clock"] for b in results]91 times_mean = [s["mean"] for s in summaries]92 times_stddev = [93 s["stddev"] if s["stddev"] is not None else float("nan") for s in summaries99 summaries = [b["summary"][args.metric] for b in results]100 means = [s["mean"] / metric_scale for s in summaries]101 stddevs = [102 s["stddev"] / metric_scale if s["stddev"] is not None else float("nan")103 for s in summaries104 ]10596 plt.errorbar(x=parameter_values, y=times_mean, yerr=times_stddev, capsize=2)106 plt.errorbar(x=parameter_values, y=means, yerr=stddevs, capsize=2)107108plt.xlabel(parameter_name)99plt.ylabel("Time [s]")109plt.ylabel(metric_label)110101if args.log_time:111if args.log_y:112 plt.yscale("log")113else:114 plt.ylim(0, None)115
10 unmodified lines
modified:scripts/plot_progression.py+14 added-9 removed
17 unmodified lines
1819import matplotlib.pyplot as plt20import numpy as np2122from plot_utils import METRICS, add_metric_argument, validate_metric232423def moving_average(times, num_runs):24 times_padded = np.pad(25 times, (num_runs // 2, num_runs - 1 - num_runs // 2), mode="edge"25def moving_average(values, num_runs):26 values_padded = np.pad(27 values, (num_runs // 2, num_runs - 1 - num_runs // 2), mode="edge"28 )29 kernel = np.ones(num_runs) / num_runs28 return np.convolve(times_padded, kernel, mode="valid")30 return np.convolve(values_padded, kernel, mode="valid")313233parser = argparse.ArgumentParser(description=__doc__)34add_metric_argument(parser)35parser.add_argument("file", help="JSON file with benchmark results")36parser.add_argument("--title", help="Plot Title")37parser.add_argument("-o", "--output", help="Save image to the given filename.")38parser.add_argument(
10 unmodified lines
49)505152args = parser.parse_args()53metric_label, metric_scale = METRICS[args.metric]5455with open(args.file) as f:56 results = json.load(f)["results"]57validate_metric(parser, results, args.metric)5859for result in results:60 label = result.get("name", result["command"])56 times = [m["time_wall_clock"]["value"] for m in result["measurements"]]57 num = len(times)61 values = [m[args.metric]["value"] / metric_scale for m in result["measurements"]]62 num = len(values)63 nums = range(num)6460 plt.scatter(x=nums, y=times, marker=".")65 plt.scatter(x=nums, y=values, marker=".")66 plt.ylim([0, None])67 plt.xlim([-1, num])6869 if not args.no_moving_average:
2 unmodified lines
72 if args.moving_average_width is None73 else args.moving_average_width74 )7571 average = moving_average(times, moving_average_width)76 average = moving_average(values, moving_average_width)77 plt.plot(nums, average, "-")7879if args.title:80 plt.title(args.title)
4 unmodified lines
85 if not args.no_moving_average:86 legend.append("moving average")87plt.legend(legend)8884plt.ylabel("Time [s]")89plt.ylabel(metric_label)9091if args.output:92 plt.savefig(args.output)93else:
1 unmodified line
added:scripts/plot_utils.py+27 added
1"""Shared metric options for the plotting scripts."""23METRICS = {4 "time_wall_clock": ("Time [s]", 1),5 "time_user": ("User CPU time [s]", 1),6 "time_system": ("System CPU time [s]", 1),7 "memory_peak_resident": ("Peak resident memory [MiB]", 1024**2),8}91011def add_metric_argument(parser):12 parser.add_argument(13 "--metric",14 choices=METRICS,15 default="time_wall_clock",16 help="Metric to plot (default: time_wall_clock). "17 "Times are in seconds; memory is in MiB.",18 )192021def validate_metric(parser, results, metric):22 for result in results:23 if metric not in result["summary"]:24 parser.error(25 f"metric {metric!r} is unavailable for "26 f"{result.get('name', result['command'])!r}"27 )
modified:scripts/plot_whisker.py+13 added-6 removed
18 unmodified lines
19import json2021import matplotlib.pyplot as plt2223from plot_utils import METRICS, add_metric_argument, validate_metric2425parser = argparse.ArgumentParser(description=__doc__)26add_metric_argument(parser)27parser.add_argument("file", help="JSON file with benchmark results")28parser.add_argument("--title", help="Plot Title")29parser.add_argument("--sort-by", choices=["median"], help="Sort method")30parser.add_argument(
1 unmodified line
32)33parser.add_argument("-o", "--output", help="Save image to the given filename.")3435args = parser.parse_args()36metric_label, metric_scale = METRICS[args.metric]3738with open(args.file, encoding="utf-8") as f:39 results = json.load(f)["results"]40validate_metric(parser, results, args.metric)4142if args.labels:43 labels = args.labels.split(",")44else:45 labels = [b.get("name", b["command"]) for b in results]41times = [[m["time_wall_clock"]["value"] for m in b["measurements"]] for b in results]46values = [47 [m[args.metric]["value"] / metric_scale for m in b["measurements"]] for b in results48]4950if args.sort_by == "median":44 medians = [b["summary"]["time_wall_clock"]["median"] for b in results]51 medians = [b["summary"][args.metric]["median"] for b in results]52 indices = sorted(range(len(labels)), key=lambda k: medians[k])53 labels = [labels[i] for i in indices]47 times = [times[i] for i in indices]54 values = [values[i] for i in indices]5556plt.figure(figsize=(10, 6), constrained_layout=True)50boxplot = plt.boxplot(times, vert=True, patch_artist=True)57boxplot = plt.boxplot(values, vert=True, patch_artist=True)58cmap = plt.get_cmap("rainbow")52colors = [cmap(val / len(times)) for val in range(len(times))]59colors = [cmap(val / len(values)) for val in range(len(values))]6061for patch, color in zip(boxplot["boxes"], colors):62 patch.set_facecolor(color)6364if args.title:65 plt.title(args.title)66plt.legend(handles=boxplot["boxes"], labels=labels, loc="best", fontsize="medium")60plt.ylabel("Time [s]")67plt.ylabel(metric_label)68plt.ylim(0, None)69plt.xticks(list(range(1, len(labels) + 1)), labels, rotation=45)70if args.output:71 plt.savefig(args.output)
2 unmodified lines