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
Provenance
- Commit
ef86c83- Tree
ebebc6e- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
f26c015
6 files changed+115 added−40 removed
modified:scripts/plot_benchmark_comparison.py+13 added-8 removed
18 unmodified lines19 20 import matplotlib.pyplot as plt21 import numpy as np22 23+from plot_utils import METRICS, add_metric_argument, validate_metric24+25 parser = argparse.ArgumentParser(description=__doc__)26+add_metric_argument(parser)27 parser.add_argument(28 "files", nargs="+", type=pathlib.Path, help="JSON files with benchmark results"29 )30 parser.add_argument("--title", help="Plot Title")2 unmodified lines33 )34 parser.add_argument("-o", "--output", help="Save image to the given filename")35 36 args = parser.parse_args()37+metric_label, metric_scale = METRICS[args.metric]38 39 commands = None40 data = []41 inputs = []42 43 if 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+ )47 48 for 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 lines78 79 if args.title:80 plt.title(args.title)81 plt.xlabel("Benchmark")77-plt.ylabel("Time [s]")82+plt.ylabel(metric_label)83 plt.legend(title="Command")84 85 if args.output:86 plt.savefig(args.output)2 unmodified linesmodified:scripts/plot_histogram.py+30 added-9 removed
14 unmodified lines15 16 import matplotlib.pyplot as plt17 import numpy as np18 19+from plot_utils import METRICS, add_metric_argument, validate_metric20+21 parser = argparse.ArgumentParser(description=__doc__)22+add_metric_argument(parser)23 parser.add_argument("file", help="JSON file with benchmark results")24 parser.add_argument("--title", help="Plot title")25 parser.add_argument(26 "--labels", help="Comma-separated list of entries for the plot legend"22 unmodified lines49 "--type", help="Type of histogram (*bar*, barstacked, step, stepfilled)"50 )51 parser.add_argument("-o", "--output", help="Save image to the given filename.")52 parser.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 )59 parser.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 )66 parser.add_argument(67 "--log-count",68 help="Use a logarithmic y-axis for the event count",69 action="store_true",70 )71 72 args = parser.parse_args()73+metric_label, metric_scale = METRICS[args.metric]74 75 with open(args.file) as f:76 results = json.load(f)["results"]77+validate_metric(parser, results, args.metric)78 79 if args.labels:80 labels = args.labels.split(",")81 else:82 labels = [b.get("name", b["command"]) for b in results]70-all_times = [71- [m["time_wall_clock"]["value"] for m in b["measurements"]] for b in results83+all_values = [84+ [m[args.metric]["value"] / metric_scale for m in b["measurements"]] for b in results85 ]86 74-t_min = float(args.t_min) if args.t_min else np.min(list(map(np.min, all_times)))75-t_max = float(args.t_max) if args.t_max else np.max(list(map(np.max, all_times)))87+value_min = (88+ args.value_min89+ if args.value_min is not None90+ else np.min(list(map(np.min, all_values)))91+)92+value_max = (93+ args.value_max94+ if args.value_max is not None95+ else np.max(list(map(np.max, all_values)))96+)97 98 bins = int(args.bins) if args.bins else "auto"99 histtype = args.type if args.type else "bar"100 101 plt.figure(figsize=(10, 5))102 plt.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 )109 plt.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 )115 95-plt.xlabel("Time [s]")116+plt.xlabel(metric_label)117 if args.title:118 plt.title(args.title)119 120 if args.log_count:8 unmodified linesmodified:scripts/plot_parametrized.py+18 added-8 removed
14 unmodified lines15 import sys16 17 import matplotlib.pyplot as plt18 19+from plot_utils import METRICS, add_metric_argument, validate_metric20+21 parser = argparse.ArgumentParser(description=__doc__)22+add_metric_argument(parser)23 parser.add_argument("file", help="JSON file with benchmark results", nargs="+")24 parser.add_argument(25 "--parameter-name",26 metavar="name",3 unmodified lines30 parser.add_argument(31 "--log-x", help="Use a logarithmic x (parameter) axis", action="store_true"32 )33 parser.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 )40 parser.add_argument(41 "--titles", help="Comma-separated list of titles for the plot legend"42 )43 parser.add_argument("-o", "--output", help="Save image to the given filename.")44 45 args = parser.parse_args()46+metric_label, metric_scale = METRICS[args.metric]47 if 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 lines86 87 for filename in args.file:88 with open(filename) as f:89 results = json.load(f)["results"]90+ validate_metric(parser, results, args.metric)91 92 (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_name98 90- 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 ]105 96- 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)107 108 plt.xlabel(parameter_name)99-plt.ylabel("Time [s]")109+plt.ylabel(metric_label)110 101-if args.log_time:111+if args.log_y:112 plt.yscale("log")113 else:114 plt.ylim(0, None)115 10 unmodified linesmodified:scripts/plot_progression.py+14 added-9 removed
17 unmodified lines18 19 import matplotlib.pyplot as plt20 import numpy as np21 22+from plot_utils import METRICS, add_metric_argument, validate_metric23 24+23-def moving_average(times, num_runs):24- times_padded = np.pad(25- times, (num_runs // 2, num_runs - 1 - num_runs // 2), mode="edge"25+def 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")31 32 33 parser = argparse.ArgumentParser(description=__doc__)34+add_metric_argument(parser)35 parser.add_argument("file", help="JSON file with benchmark results")36 parser.add_argument("--title", help="Plot Title")37 parser.add_argument("-o", "--output", help="Save image to the given filename.")38 parser.add_argument(10 unmodified lines49 )50 51 52 args = parser.parse_args()53+metric_label, metric_scale = METRICS[args.metric]54 55 with open(args.file) as f:56 results = json.load(f)["results"]57+validate_metric(parser, results, args.metric)58 59 for 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)64 60- 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])68 69 if not args.no_moving_average:2 unmodified lines72 if args.moving_average_width is None73 else args.moving_average_width74 )75 71- average = moving_average(times, moving_average_width)76+ average = moving_average(values, moving_average_width)77 plt.plot(nums, average, "-")78 79 if args.title:80 plt.title(args.title)4 unmodified lines85 if not args.no_moving_average:86 legend.append("moving average")87 plt.legend(legend)88 84-plt.ylabel("Time [s]")89+plt.ylabel(metric_label)90 91 if args.output:92 plt.savefig(args.output)93 else:1 unmodified lineadded:scripts/plot_utils.py+27 added
1+"""Shared metric options for the plotting scripts."""2+3+METRICS = {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+}9+10+11+def 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+ )19+20+21+def 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 lines19 import json20 21 import matplotlib.pyplot as plt22 23+from plot_utils import METRICS, add_metric_argument, validate_metric24+25 parser = argparse.ArgumentParser(description=__doc__)26+add_metric_argument(parser)27 parser.add_argument("file", help="JSON file with benchmark results")28 parser.add_argument("--title", help="Plot Title")29 parser.add_argument("--sort-by", choices=["median"], help="Sort method")30 parser.add_argument(1 unmodified line32 )33 parser.add_argument("-o", "--output", help="Save image to the given filename.")34 35 args = parser.parse_args()36+metric_label, metric_scale = METRICS[args.metric]37 38 with open(args.file, encoding="utf-8") as f:39 results = json.load(f)["results"]40+validate_metric(parser, results, args.metric)41 42 if args.labels:43 labels = args.labels.split(",")44 else:45 labels = [b.get("name", b["command"]) for b in results]41-times = [[m["time_wall_clock"]["value"] for m in b["measurements"]] for b in results]46+values = [47+ [m[args.metric]["value"] / metric_scale for m in b["measurements"]] for b in results48+]49 50 if 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]55 56 plt.figure(figsize=(10, 6), constrained_layout=True)50-boxplot = plt.boxplot(times, vert=True, patch_artist=True)57+boxplot = plt.boxplot(values, vert=True, patch_artist=True)58 cmap = plt.get_cmap("rainbow")52-colors = [cmap(val / len(times)) for val in range(len(times))]59+colors = [cmap(val / len(values)) for val in range(len(values))]60 61 for patch, color in zip(boxplot["boxes"], colors):62 patch.set_facecolor(color)63 64 if args.title:65 plt.title(args.title)66 plt.legend(handles=boxplot["boxes"], labels=labels, loc="best", fontsize="medium")60-plt.ylabel("Time [s]")67+plt.ylabel(metric_label)68 plt.ylim(0, None)69 plt.xticks(list(range(1, len(labels) + 1)), labels, rotation=45)70 if args.output:71 plt.savefig(args.output)2 unmodified lines