596 lines
17 KiB
Python
596 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
# Generates markdown tables from criterion textual output.
|
|
# Outputs to stdout or to the README.md file if provided as an argument.
|
|
|
|
import os
|
|
import re
|
|
import sys
|
|
from dataclasses import dataclass
|
|
from typing import Dict, List, Optional, Tuple
|
|
|
|
import matplotlib.pyplot as plt
|
|
import numpy as np
|
|
from tabulate import tabulate
|
|
|
|
MARKER = "<!-- AUTOGENERATED MARKER -->\n"
|
|
KINDS = ["lex", "parse", "lower"]
|
|
|
|
|
|
@dataclass
|
|
class BenchmarkEntry:
|
|
"""Represents a single benchmark entry with parser, kind, and timing information."""
|
|
|
|
bench_name: str
|
|
parser: str
|
|
kind: str
|
|
time_str: str
|
|
time_ns: int
|
|
|
|
|
|
class BenchmarkData:
|
|
"""Encapsulates benchmark data and provides methods for analysis and visualization."""
|
|
|
|
def __init__(self, entries: List[BenchmarkEntry]) -> None:
|
|
"""Initialize with a list of benchmark entries."""
|
|
self.entries = entries
|
|
self.parsers = sorted(set(entry.parser for entry in entries))
|
|
self.benchmarks = sorted(set(entry.bench_name for entry in entries))
|
|
self.kinds = KINDS
|
|
|
|
# Filter out the "empty" benchmark
|
|
self.benchmarks = [b for b in self.benchmarks if b != "empty"]
|
|
|
|
def get_entries(
|
|
self,
|
|
bench_name: Optional[str] = None,
|
|
parser: Optional[str] = None,
|
|
kind: Optional[str] = None,
|
|
) -> List[BenchmarkEntry]:
|
|
"""Get entries filtered by benchmark name, parser, and/or kind."""
|
|
result = self.entries
|
|
if bench_name:
|
|
result = [e for e in result if e.bench_name == bench_name]
|
|
if parser:
|
|
result = [e for e in result if e.parser == parser]
|
|
if kind:
|
|
result = [e for e in result if e.kind == kind]
|
|
return result
|
|
|
|
def get_available_parsers(self, kind: str) -> List[str]:
|
|
"""Get parsers that have data for a specific kind."""
|
|
available_parsers = []
|
|
for parser in self.get_sorted_parsers()[kind]:
|
|
if any(x.parser == parser and x.kind == kind for x in self.entries):
|
|
available_parsers.append(parser)
|
|
return available_parsers
|
|
|
|
def get_slowest_time(self, bench_name: str, kind: str) -> int:
|
|
"""Get the slowest time for a specific benchmark and kind."""
|
|
entries = self.get_entries(bench_name=bench_name, kind=kind)
|
|
if not entries:
|
|
return 0
|
|
return max(e.time_ns for e in entries)
|
|
|
|
def calculate_parser_avg_times(self) -> Dict[str, Dict[str, float]]:
|
|
"""Calculate average times for each parser and kind."""
|
|
parser_avg_times = {kind: {} for kind in self.kinds}
|
|
|
|
for kind in self.kinds:
|
|
for parser in self.parsers:
|
|
entries = self.get_entries(parser=parser, kind=kind)
|
|
if entries:
|
|
avg_time = sum(e.time_ns for e in entries) / len(entries)
|
|
parser_avg_times[kind][parser] = avg_time
|
|
|
|
return parser_avg_times
|
|
|
|
def calculate_benchmark_avg_times(self) -> Dict[str, Dict[str, float]]:
|
|
"""Calculate average times for each benchmark and kind."""
|
|
bench_avg_times = {kind: {} for kind in self.kinds}
|
|
|
|
for kind in self.kinds:
|
|
for bench_name in self.benchmarks:
|
|
entries = self.get_entries(bench_name=bench_name, kind=kind)
|
|
if entries:
|
|
avg_time = sum(e.time_ns for e in entries) / len(entries)
|
|
bench_avg_times[kind][bench_name] = avg_time
|
|
|
|
return bench_avg_times
|
|
|
|
def get_sorted_parsers(self) -> Dict[str, List[str]]:
|
|
"""Get parsers sorted by average time (fastest first)."""
|
|
parser_avg_times = self.calculate_parser_avg_times()
|
|
|
|
return {
|
|
kind: sorted(
|
|
self.parsers,
|
|
key=lambda p: parser_avg_times[kind].get(p, float("inf")),
|
|
reverse=True,
|
|
)
|
|
for kind in self.kinds
|
|
}
|
|
|
|
def get_sorted_benchmarks(self) -> Dict[str, List[str]]:
|
|
"""Get benchmarks sorted by average time (fastest first)."""
|
|
bench_avg_times = self.calculate_benchmark_avg_times()
|
|
|
|
return {
|
|
kind: sorted(
|
|
self.benchmarks,
|
|
key=lambda b: bench_avg_times[kind].get(b, float("inf")),
|
|
)
|
|
for kind in self.kinds
|
|
}
|
|
|
|
def apply_solc_correction(self) -> None:
|
|
"""Apply correction to solc parser times to remove base overhead."""
|
|
# Find base solc time from empty benchmark
|
|
base_solc_entry = next(
|
|
(e for e in self.entries if e.bench_name == "empty" and e.parser == "solc"),
|
|
None,
|
|
)
|
|
|
|
if not base_solc_entry:
|
|
raise ValueError("Couldn't find base solc time")
|
|
|
|
# Subtract base overhead (keeping 1us)
|
|
base_solc_ns = base_solc_entry.time_ns - 1_000
|
|
|
|
# Apply correction to all solc entries
|
|
for entry in self.entries:
|
|
if entry.parser == "solc":
|
|
entry.time_ns -= base_solc_ns
|
|
entry.time_str = format_ns(entry.time_ns)
|
|
|
|
|
|
def main() -> None:
|
|
"""Main function to process benchmark data and generate output."""
|
|
out_file = sys.argv[1] if len(sys.argv) > 1 else None
|
|
|
|
# Read and preprocess input
|
|
lines = read_input()
|
|
if not lines:
|
|
return
|
|
|
|
# Extract benchmark information
|
|
benchmarks = extract_benchmarks(lines)
|
|
if not benchmarks:
|
|
return
|
|
|
|
# Extract timing data
|
|
data = extract_timing_data(lines, benchmarks)
|
|
|
|
# Apply solc base overhead correction
|
|
data.apply_solc_correction()
|
|
|
|
# Generate output
|
|
out_s = ""
|
|
|
|
# Generate plots
|
|
plot_paths = plot_benchmark_times(data)
|
|
|
|
# Add relative performance charts
|
|
for kind in KINDS:
|
|
plot_path = plot_paths.get(f"{kind}_relative")
|
|
if plot_path:
|
|
out_s += (
|
|
f"})\n\n"
|
|
)
|
|
|
|
# Generate markdown tables
|
|
out_s += generate_markdown_tables(data, benchmarks)
|
|
|
|
out_s = out_s.rstrip()
|
|
|
|
# Replace the marker with the new output, or print to stdout
|
|
if out_file:
|
|
with open(out_file, "r") as f:
|
|
content = f.read()
|
|
idx = content.index(MARKER) + len(MARKER)
|
|
with open(out_file, "w") as f:
|
|
f.write(content[:idx] + "\n" + out_s + "\n")
|
|
else:
|
|
print(out_s)
|
|
|
|
|
|
def read_input() -> List[str]:
|
|
"""Read and preprocess input from stdin."""
|
|
lines = sys.stdin.readlines()
|
|
if not lines:
|
|
return []
|
|
|
|
# Skip header lines
|
|
while lines and ":" not in lines[0]:
|
|
lines = lines[1:]
|
|
|
|
# Filter out warning lines
|
|
lines = list(filter(lambda x: "Warning" not in x, lines))
|
|
return lines
|
|
|
|
|
|
def extract_benchmarks(lines: List[str]) -> List[Tuple[str, int, int]]:
|
|
"""Extract benchmark information from input lines."""
|
|
benchmark_re = re.compile(r"(\w+): (\d+) LoC, (\d+) bytes")
|
|
benchmarks = []
|
|
|
|
for line in lines:
|
|
if line.strip() == "":
|
|
break
|
|
match = benchmark_re.match(line)
|
|
if match:
|
|
name, loc, bytes = match.groups()
|
|
benchmarks.append((name, int(loc), int(bytes)))
|
|
|
|
return benchmarks
|
|
|
|
|
|
def extract_timing_data(
|
|
lines: List[str], benchmarks: List[Tuple[str, int, int]]
|
|
) -> BenchmarkData:
|
|
"""Extract timing data from input lines."""
|
|
time = r"(\s*[\d\.]+ \w+)"
|
|
data_re = re.compile(
|
|
rf"parser/(.+?)/(.+?)/(.+?)\s*time:\s*\n?\s*\[{time}{time}{time}\]",
|
|
flags=re.MULTILINE,
|
|
)
|
|
|
|
entries = []
|
|
|
|
for match in data_re.findall("\n".join(lines)):
|
|
bench_name, parser, kind, _time1, time2, _time3 = match
|
|
time_ns = parse_time_s(time2)
|
|
entries.append(BenchmarkEntry(bench_name, parser, kind, time2, time_ns))
|
|
|
|
return BenchmarkData(entries)
|
|
|
|
|
|
def generate_markdown_tables(
|
|
data: BenchmarkData, benchmarks: List[Tuple[str, int, int]]
|
|
) -> str:
|
|
"""
|
|
Generate markdown tables for each benchmark and kind.
|
|
|
|
Args:
|
|
data: BenchmarkData object
|
|
benchmarks: List of (bench_name, loc, bytes) tuples
|
|
|
|
Returns:
|
|
String containing markdown tables
|
|
"""
|
|
out_s = ""
|
|
for bench_name, loc, bytes in benchmarks:
|
|
out_s += f"### {bench_name} ({loc} LoC, {bytes} bytes)\n\n"
|
|
|
|
for kind in KINDS:
|
|
table = []
|
|
table.append(
|
|
[
|
|
"Parser",
|
|
"Relative",
|
|
"Time",
|
|
"LoC/s",
|
|
"Bytes/s",
|
|
]
|
|
)
|
|
|
|
# Find the slowest parser for this benchmark and kind
|
|
slowest_time = data.get_slowest_time(bench_name, kind)
|
|
|
|
# Add data for each parser
|
|
for parser in data.parsers:
|
|
entry = next(
|
|
(
|
|
e
|
|
for e in data.entries
|
|
if e.bench_name == bench_name
|
|
and e.parser == parser
|
|
and e.kind == kind
|
|
),
|
|
None,
|
|
)
|
|
if not entry:
|
|
continue
|
|
|
|
time_ns = entry.time_ns
|
|
# Calculate relative speed compared to slowest parser (inverted)
|
|
relative = format_number(slowest_time / time_ns) + "x"
|
|
time_s = entry.time_str
|
|
loc_s = get_per_second(loc, time_ns)
|
|
bytes_s = get_per_second(bytes, time_ns)
|
|
table.append(
|
|
[
|
|
parser,
|
|
relative,
|
|
time_s,
|
|
loc_s,
|
|
bytes_s,
|
|
]
|
|
)
|
|
|
|
if len(table) <= 1:
|
|
continue
|
|
|
|
# Sort by relative speed (fastest first)
|
|
table[1:] = sorted(table[1:], key=lambda x: float(x[1][:-1]), reverse=True)
|
|
|
|
out_s += f"#### {kind.capitalize()}\n"
|
|
out_s += tabulate(table, headers="firstrow", tablefmt="pipe")
|
|
out_s += "\n\n"
|
|
|
|
return out_s
|
|
|
|
|
|
def plot_benchmark_times(data: BenchmarkData) -> Dict[str, str]:
|
|
"""
|
|
Plot the parsing and lexing times on a log chart for all parsers.
|
|
|
|
Args:
|
|
data: BenchmarkData object
|
|
|
|
Returns:
|
|
Dictionary with paths to the generated plot images
|
|
"""
|
|
# Get sorted benchmarks and parsers
|
|
sorted_bench_names = data.get_sorted_benchmarks()
|
|
|
|
# Create output directory if it doesn't exist
|
|
output_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
|
|
# Define a consistent color map for all parsers
|
|
color_map = {parser: plt.cm.tab10(i % 10) for i, parser in enumerate(data.parsers)}
|
|
|
|
plot_paths = {}
|
|
|
|
# Generate separate plots for each kind
|
|
for kind in KINDS:
|
|
# Filter parsers that have data for this kind
|
|
available_parsers = data.get_available_parsers(kind)
|
|
|
|
# Generate absolute time plots
|
|
plot_paths[kind] = create_plot(
|
|
data,
|
|
kind,
|
|
sorted_bench_names[kind],
|
|
available_parsers,
|
|
output_dir,
|
|
color_map,
|
|
)
|
|
|
|
# Generate relative performance plots (if more than one parser is available)
|
|
if len(available_parsers) > 1:
|
|
plot_paths[f"{kind}_relative"] = create_relative_plot(
|
|
data,
|
|
kind,
|
|
sorted_bench_names[kind],
|
|
available_parsers,
|
|
output_dir,
|
|
color_map,
|
|
)
|
|
|
|
return plot_paths
|
|
|
|
|
|
def create_plot(
|
|
data: BenchmarkData,
|
|
kind: str,
|
|
sorted_bench_names: List[str],
|
|
available_parsers: List[str],
|
|
output_dir: str,
|
|
color_map,
|
|
) -> str:
|
|
"""Create a single plot for a specific kind."""
|
|
# Create a figure
|
|
plt.figure(figsize=(12, 8))
|
|
ax = plt.gca()
|
|
|
|
# Set up the plot
|
|
ax.set_title(f"Time to {kind} (log scale)")
|
|
ax.set_xlabel("Benchmark")
|
|
ax.set_ylabel("Time (ns)")
|
|
ax.set_yscale("log")
|
|
|
|
# Set up x-axis positions
|
|
x = np.arange(len(sorted_bench_names))
|
|
width = 0.8 / len(available_parsers) if available_parsers else 0.8
|
|
|
|
# Plot each parser
|
|
for i, parser in enumerate(available_parsers):
|
|
times = []
|
|
for bench_name in sorted_bench_names:
|
|
# Find the time for this parser and benchmark
|
|
entry = next(
|
|
(
|
|
e
|
|
for e in data.entries
|
|
if e.bench_name == bench_name
|
|
and e.parser == parser
|
|
and e.kind == kind
|
|
),
|
|
None,
|
|
)
|
|
if entry:
|
|
times.append(entry.time_ns) # time_ns
|
|
else:
|
|
times.append(np.nan) # Missing data
|
|
|
|
# Plot the data with consistent color
|
|
ax.bar(
|
|
x + i * width - 0.4 + width / 2,
|
|
times,
|
|
width,
|
|
label=parser,
|
|
color=color_map[parser],
|
|
)
|
|
|
|
# Set x-axis labels
|
|
ax.set_xticks(x)
|
|
ax.set_xticklabels(sorted_bench_names, rotation=45, ha="right")
|
|
|
|
# Add grid for better readability
|
|
ax.grid(True, axis="y", linestyle="--", alpha=0.7)
|
|
|
|
# Add legend
|
|
ax.legend()
|
|
|
|
# Adjust layout to prevent label cutoff
|
|
plt.tight_layout()
|
|
|
|
# Save the figure
|
|
output_path = os.path.join(output_dir, f"{kind}_benchmark_times.png")
|
|
plt.savefig(output_path, dpi=300)
|
|
print(f"{kind.capitalize()} plot saved to {output_path}")
|
|
|
|
# Close the figure to free memory
|
|
plt.close()
|
|
|
|
return output_path
|
|
|
|
|
|
def create_relative_plot(
|
|
data: BenchmarkData,
|
|
kind: str,
|
|
sorted_bench_names: List[str],
|
|
available_parsers: List[str],
|
|
output_dir: str,
|
|
color_map,
|
|
) -> str:
|
|
"""
|
|
Create a relative performance plot showing speedup factors compared to the slowest parser.
|
|
|
|
This visualization better highlights the performance differences between parsers
|
|
by showing how many times faster each parser is compared to the slowest one.
|
|
"""
|
|
# Create a figure
|
|
plt.figure(figsize=(12, 8))
|
|
ax = plt.gca()
|
|
|
|
# Set up the plot
|
|
ax.set_title(f"Relative {kind} performance (higher is better)")
|
|
ax.set_xlabel("Benchmark")
|
|
ax.set_ylabel("Speedup factor (x faster than slowest)")
|
|
|
|
# Set up x-axis positions
|
|
x = np.arange(len(sorted_bench_names))
|
|
width = 0.8 / len(available_parsers)
|
|
|
|
# Find the slowest parser for each benchmark
|
|
slowest_times = {}
|
|
for bench_name in sorted_bench_names:
|
|
slowest_times[bench_name] = data.get_slowest_time(bench_name, kind)
|
|
|
|
# Plot each parser
|
|
for i, parser in enumerate(available_parsers):
|
|
speedups = []
|
|
for bench_name in sorted_bench_names:
|
|
# Find the time for this parser and benchmark
|
|
entry = next(
|
|
(
|
|
e
|
|
for e in data.entries
|
|
if e.bench_name == bench_name
|
|
and e.parser == parser
|
|
and e.kind == kind
|
|
),
|
|
None,
|
|
)
|
|
if entry:
|
|
# Calculate speedup factor compared to slowest parser
|
|
speedup = slowest_times[bench_name] / entry.time_ns
|
|
speedups.append(speedup)
|
|
else:
|
|
speedups.append(np.nan) # Missing data
|
|
|
|
# Plot the data with consistent color
|
|
ax.bar(
|
|
x + i * width - 0.4 + width / 2,
|
|
speedups,
|
|
width,
|
|
label=parser,
|
|
color=color_map[parser],
|
|
)
|
|
|
|
# Set x-axis labels
|
|
ax.set_xticks(x)
|
|
ax.set_xticklabels(sorted_bench_names, rotation=45, ha="right")
|
|
|
|
# Add grid for better readability
|
|
ax.grid(True, axis="y", linestyle="--", alpha=0.7)
|
|
|
|
# Add legend
|
|
ax.legend()
|
|
|
|
# Adjust layout to prevent label cutoff
|
|
plt.tight_layout()
|
|
|
|
# Save the figure
|
|
output_path = os.path.join(output_dir, f"{kind}_relative_performance.png")
|
|
plt.savefig(output_path, dpi=300)
|
|
print(f"{kind.capitalize()} relative performance plot saved to {output_path}")
|
|
|
|
# Close the figure to free memory
|
|
plt.close()
|
|
|
|
return output_path
|
|
|
|
|
|
def parse_time_s(time: str) -> int:
|
|
"""Parse a time string into nanoseconds."""
|
|
value, unit = time.strip().split(" ")
|
|
value = float(value)
|
|
if unit == "s":
|
|
return int(value * 1_000_000_000)
|
|
elif unit == "ms":
|
|
return int(value * 1_000_000)
|
|
elif unit == "us" or unit == "µs":
|
|
return int(value * 1_000)
|
|
elif unit == "ns":
|
|
return int(value * 1)
|
|
else:
|
|
raise ValueError(f"Unknown unit: {unit}")
|
|
|
|
|
|
def get_per_second(total: int, ns: int) -> str:
|
|
"""Calculate items per second based on total and nanoseconds."""
|
|
if total == 0 or ns == -1:
|
|
return "N/A"
|
|
|
|
s = ns / 1_000_000_000
|
|
return format_number(total / s)
|
|
|
|
|
|
def format_number(n: float) -> str:
|
|
"""Format a number with appropriate suffix (K, M, B)."""
|
|
if n >= 1_000_000_000:
|
|
n /= 1_000_000_000
|
|
s = "B"
|
|
elif n >= 1_000_000:
|
|
n /= 1_000_000
|
|
s = "M"
|
|
elif n >= 1_000:
|
|
n /= 1_000
|
|
s = "K"
|
|
else:
|
|
s = ""
|
|
return f"{n:.2f}{s}"
|
|
|
|
|
|
def format_ns(ns: int) -> str:
|
|
"""Format nanoseconds with appropriate unit (ns, µs, ms, s)."""
|
|
if ns >= 1_000_000_000:
|
|
ns /= 1_000_000_000
|
|
s = "s"
|
|
elif ns >= 1_000_000:
|
|
ns /= 1_000_000
|
|
s = "ms"
|
|
elif ns >= 1_000:
|
|
ns /= 1_000
|
|
s = "µs"
|
|
else:
|
|
s = "ns"
|
|
return f"{ns:f}"[:6] + " " + s
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|