Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,24 @@ after each iteration with the default harness.
./run_benchmarks.rb --yjit-stats=code_region_size,yjit_alloc_size
```

## Statistical significance

`--pvalue` adds a p-value and significance column to each comparison and marks
the ratio with `*` (p < 0.05), `**` (p < 0.01) or `***` (p < 0.001), from a
Welch's t-test. The iterations of one process share its heap layout, GC timing
and JIT decisions, so they are not independent samples: two processes of the
same Ruby often differ by more than their iterations vary. The test therefore
compares the means of separate processes, and needs `--runs`:

```sh
# Run each benchmark in 5 processes per Ruby, interleaved
./run_benchmarks.rb --chruby "before;after" --runs 5 --pvalue railsbench
```

`--runs N` multiplies the benchmarking time by N. The timing columns then
report all measured iterations of the N processes. With one process per Ruby,
the p-value is N/A.

## Measuring memory usage

`--rss` option of `run_benchmarks.rb` allows you to measure RSS (resident set size).
Expand Down
10 changes: 9 additions & 1 deletion lib/argument_parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class ArgumentParser
:with_pre_init,
:pvalue,
:interleave,
:runs,
:zjit_stats,
keyword_init: true
)
Expand Down Expand Up @@ -153,14 +154,20 @@ def parse(argv)
args.rss = true
end

opts.on("--pvalue", "show p-value and significance columns for each comparison") do
opts.on("--pvalue", "show p-value and significance columns for each comparison (needs --runs=N with N >= 2)") do
args.pvalue = true
end

opts.on("--interleave", "run benchmarks interleaved across executables to reduce thermal drift") do
args.interleave = true
end

opts.on("--runs=N", Integer, "run each benchmark in N processes per executable, interleaved; --pvalue compares the per-process means (default: 1)") do |n|
abort "--runs must be at least 1" if n < 1
args.runs = n
args.interleave = true if n > 1
end

opts.on("--graph", "generate a graph image of benchmark results") do
args.graph = true
end
Expand Down Expand Up @@ -257,6 +264,7 @@ def default_args
rss: false,
pvalue: false,
interleave: false,
runs: 1,
zjit_stats: [],
graph: false,
no_pinning: false,
Expand Down
14 changes: 13 additions & 1 deletion lib/benchmark_runner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ def output_path(out_path_dir, out_override: nil)
end
end

def merge_runs(blobs)
return blobs.first if blobs.size == 1

merged = blobs.first.to_h do |key, value|
series = blobs.map { |blob| blob[key] }
[key, series.all?(Array) ? series.flatten(1) : value]
end
merged['warmup_itrs_per_run'] = blobs.map { |blob| Array(blob['warmup']).size }
merged['bench_itrs_per_run'] = blobs.map { |blob| blob['bench'].size }
merged
end

# Write benchmark data to JSON file
def write_json(output_path, ruby_descriptions, bench_data)
out_json_path = "#{output_path}.json"
Expand Down Expand Up @@ -102,7 +114,7 @@ def build_output_text(ruby_descriptions, table, format, bench_failures, include_
output_str << "- Scenario memory shows #{base_name} → comparison values, not ratios. Lower is better.\n"
end
if include_pvalue
output_str << "- ***: p < 0.001, **: p < 0.01, *: p < 0.05 (Welch's t-test)\n"
output_str << "- ***: p < 0.001, **: p < 0.01, *: p < 0.05 (Welch's t-test over the per-process means of --runs; N/A with a single process)\n"
end
end
gc_headers = sections.flat_map { |section| Array(section[:gc_tables]).flat_map { |gc_table| gc_table[:rows].first } }
Expand Down
48 changes: 36 additions & 12 deletions lib/benchmark_runner/cli.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,26 +74,50 @@ def run
bench_harnesses = suite.benchmarks.each_with_object({}) do |entry, h|
h[entry.name] = suite.harness_for(entry.name)
end
if args.runs > 1 && bench_harnesses.value?(BenchmarkSuite::RACTOR_HARNESS)
abort "--runs does not support the Ractor harness yet: its per-Ractor-count results are not merged across processes"
end
if args.pvalue && bench_harnesses.value?("callgrind")
abort "--pvalue does not support the callgrind harness: it tests wall times, which Valgrind slows and distorts. Compare the instruction counts in the profiles instead"
end
if args.pvalue && args.runs < 2
warn "#{BOLD}WARNING: --pvalue needs --runs=N with N >= 2. Iterations of one process are not independent samples, so p-values will be N/A.#{RESET}"
end

if args.interleave
args.executables.each_key { |name| bench_data[name] = {} }
entries = suite.benchmarks

runs = args.runs
rounds = 0

entries.each_with_index do |entry, idx|
# Alternate executable order to cancel cache-warming bias
exes = ruby_descriptions.keys
exes = exes.reverse if idx.odd?

exes.each do |name|
puts("Running benchmark \"#{entry.name}\" [#{name}] (#{idx+1}/#{entries.length})")
result = suite.run_benchmark(entry, ruby: args.executables[name], ruby_description: ruby_descriptions[name])
if result[:data]
bench_data[name][entry.name] = result[:data]
else
bench_failures[name] ||= {}
bench_failures[name][entry.name] = result[:failure]
blobs = Hash.new { |h, name| h[name] = [] }

runs.times do |run|
# Alternate executable order to cancel cache-warming bias
exes = ruby_descriptions.keys
exes = exes.reverse if rounds.odd?
rounds += 1

exes.each do |name|
next if bench_failures[name]&.key?(entry.name)

run_label = runs > 1 ? ", run #{run + 1}/#{runs}" : ""
puts("Running benchmark \"#{entry.name}\" [#{name}] (#{idx+1}/#{entries.length}#{run_label})")
result = suite.run_benchmark(entry, ruby: args.executables[name], ruby_description: ruby_descriptions[name])
if result[:data]
blobs[name] << result[:data]
else
bench_failures[name] ||= {}
bench_failures[name][entry.name] = result[:failure]
end
end
end

blobs.each do |name, runs_data|
bench_data[name][entry.name] = BenchmarkRunner.merge_runs(runs_data) unless bench_failures[name]&.key?(entry.name)
end
end
else
args.executables.each do |name, executable|
Expand Down
57 changes: 46 additions & 11 deletions lib/results_table_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,13 @@ def build_gc_comparison_tables(label_header)
count: gc_count_series(data),
global: data['gc_global_count_bench'],
compact: data['gc_controller_compact_count_bench'],
runs: data['bench_itrs_per_run'],
}
end

base, *others = series_by_exe
others.each_with_index do |other, i|
next unless gc_activity?(*base.values, *other.values)
next unless gc_activity?(*base.except(:runs).values, *other.except(:runs).values)

labels = gc_label_cells(entry)
labels << @other_names[i] if include_gc_comparison_name?
Expand All @@ -166,11 +167,11 @@ def build_gc_comparison_tables(label_header)
def gc_ratio_columns
columns = []
if include_gc_total_time?
columns << ["gc/iter", ->(base, other) { ratio_cell(gc_ratio(base[:total], other[:total])) }]
columns << ["gc/iter", ->(base, other) { ratio_cell(gc_ratio(base, other, :total)) }]
columns << ["gc/GC", ->(base, other) { ratio_cell(per_gc_ratio(base, other, :total)) }]
end
columns << ["mark/iter", ->(base, other) { ratio_cell(gc_ratio(base[:mark], other[:mark])) }]
columns << ["sweep/iter", ->(base, other) { ratio_cell(gc_ratio(base[:sweep], other[:sweep])) }]
columns << ["mark/iter", ->(base, other) { ratio_cell(gc_ratio(base, other, :mark)) }]
columns << ["sweep/iter", ->(base, other) { ratio_cell(gc_ratio(base, other, :sweep)) }]
columns << ["mark/GC", ->(base, other) { ratio_cell(per_gc_ratio(base, other, :mark)) }]
columns << ["sweep/GC", ->(base, other) { ratio_cell(per_gc_ratio(base, other, :sweep)) }]
columns
Expand Down Expand Up @@ -425,7 +426,7 @@ def build_stat_cells(bench_name)
row = []
build_base_columns(row, base_t, base_rss_cell, zjit_stat_values, 0)
build_comparison_columns(row, other_ts, other_rss_cells, zjit_stat_values)
build_ratio_columns(row, base_t0, other_t0s, base_t, other_ts)
build_ratio_columns(row, bench_name, base_t0, other_t0s, base_t, other_ts)
build_rss_ratio_columns(row, base_rss, other_rsss)

row
Expand Down Expand Up @@ -455,12 +456,14 @@ def format_time_with_stddev(values)
"%.1f ± %.1f%%" % [mean(values), stddev_percent(values)]
end

def build_ratio_columns(row, base_t0, other_t0s, base_t, other_ts)
def build_ratio_columns(row, bench_name, base_t0, other_t0s, base_t, other_ts)
ratio_1sts = other_t0s.map { |other_t0| base_t0 / other_t0 }
row.concat(ratio_1sts)

other_ts.each do |other_t|
pval = @include_pvalue ? Stats.welch_p_value(base_t, other_t) : nil
base_runs = bench_data_for(@base_name, bench_name)['bench_itrs_per_run']
other_ts.each_with_index do |other_t, i|
other_runs = bench_data_for(@other_names[i], bench_name)['bench_itrs_per_run']
pval = p_value(base_t, base_runs, other_t, other_runs)
row << format_ratio(mean(base_t) / mean(other_t), pval)
if @include_pvalue
row << format_p_value(pval)
Expand Down Expand Up @@ -563,14 +566,40 @@ def scalar_ratio(base, other)
format_ratio(base / other, nil)
end

def gc_ratio(base, other)
def gc_ratio(base_series, other_series, key)
base = base_series[key]
other = other_series[key]
return "N/A" unless numeric_series?(base) && numeric_series?(other)
return "N/A" if mean(other) == 0.0

pval = @include_pvalue ? Stats.welch_p_value(base, other) : nil
pval = p_value(base, base_series[:runs], other, other_series[:runs])
format_ratio(mean(base) / mean(other), pval)
end

# Iterations of one process share its heap, GC timing and JIT, so the test compares process means.
def p_value(base, base_runs, other, other_runs)
return nil unless @include_pvalue

base_means = run_means(base, base_runs)
other_means = run_means(other, other_runs)
base_means && other_means ? Stats.welch_p_value(base_means, other_means) : nil
end

def run_means(series, itrs_per_run)
split_runs(series, itrs_per_run)&.map { |values| mean(values) }
end

def split_runs(series, itrs_per_run)
return nil unless itrs_per_run.is_a?(Array) && series.is_a?(Array) && itrs_per_run.sum == series.size

offset = 0
itrs_per_run.map do |size|
values = series[offset, size]
offset += size
values
end
end

def format_ratio(ratio, pval)
sym = significance_symbol(pval)
formatted = "%.3f" % ratio
Expand Down Expand Up @@ -618,7 +647,13 @@ def significance_level(pval)
def extract_first_iteration_times(bench_name)
@executable_names.map do |name|
data = bench_data_for(name, bench_name)
(data['warmup'][0] || data['bench'][0]) * SECONDS_TO_MS
bench_runs = split_runs(data['bench'], data['bench_itrs_per_run'])
if bench_runs
warmup_runs = split_runs(data['warmup'], data['warmup_itrs_per_run'])
mean(bench_runs.each_index.map { |i| (warmup_runs && warmup_runs[i][0]) || bench_runs[i][0] }) * SECONDS_TO_MS
else
(data['warmup'][0] || data['bench'][0]) * SECONDS_TO_MS
end
end
end

Expand Down
24 changes: 24 additions & 0 deletions test/argument_parser_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,30 @@ def setup_mock_ruby(path)
end
end

describe '--runs option' do
it 'sets runs and interleaves the runs' do
parser = ArgumentParser.new
args = parser.parse(['--runs=3'])

assert_equal 3, args.runs
assert_equal true, args.interleave
end

it 'defaults to one run' do
parser = ArgumentParser.new
args = parser.parse([])

assert_equal 1, args.runs
end

it 'does not interleave a single run' do
parser = ArgumentParser.new
args = parser.parse(['--runs=1'])

assert_equal false, args.interleave
end
end

describe '--interleave option' do
it 'sets interleave flag' do
parser = ArgumentParser.new
Expand Down
Loading
Loading