diff --git a/README.md b/README.md index 9e438619..56f62b3c 100644 --- a/README.md +++ b/README.md @@ -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). diff --git a/lib/argument_parser.rb b/lib/argument_parser.rb index e381bd39..9bb8c485 100644 --- a/lib/argument_parser.rb +++ b/lib/argument_parser.rb @@ -25,6 +25,7 @@ class ArgumentParser :with_pre_init, :pvalue, :interleave, + :runs, :zjit_stats, keyword_init: true ) @@ -153,7 +154,7 @@ 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 @@ -161,6 +162,12 @@ def parse(argv) 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 @@ -257,6 +264,7 @@ def default_args rss: false, pvalue: false, interleave: false, + runs: 1, zjit_stats: [], graph: false, no_pinning: false, diff --git a/lib/benchmark_runner.rb b/lib/benchmark_runner.rb index 43c427ff..8f60cc00 100644 --- a/lib/benchmark_runner.rb +++ b/lib/benchmark_runner.rb @@ -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" @@ -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 } } diff --git a/lib/benchmark_runner/cli.rb b/lib/benchmark_runner/cli.rb index bf210402..d75c90d9 100644 --- a/lib/benchmark_runner/cli.rb +++ b/lib/benchmark_runner/cli.rb @@ -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| diff --git a/lib/results_table_builder.rb b/lib/results_table_builder.rb index 6f48a09a..d2f95477 100644 --- a/lib/results_table_builder.rb +++ b/lib/results_table_builder.rb @@ -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? @@ -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 @@ -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 @@ -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) @@ -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 @@ -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 diff --git a/test/argument_parser_test.rb b/test/argument_parser_test.rb index ea41d624..bbeffe84 100644 --- a/test/argument_parser_test.rb +++ b/test/argument_parser_test.rb @@ -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 diff --git a/test/benchmark_runner_cli_test.rb b/test/benchmark_runner_cli_test.rb index ef039e3c..36037820 100644 --- a/test/benchmark_runner_cli_test.rb +++ b/test/benchmark_runner_cli_test.rb @@ -51,6 +51,7 @@ def create_args(overrides = {}) excludes: [], rss: false, interleave: false, + runs: 1, graph: false, no_pinning: true, turbo: true, @@ -632,6 +633,93 @@ def create_args(overrides = {}) end end + it 'runs each benchmark in several processes with --runs' do + Dir.mktmpdir do |tmpdir| + args = create_args( + name_filters: ['fib'], + out_path: tmpdir, + interleave: true, + runs: 2 + ) + + cli = BenchmarkRunner::CLI.new(args) + capture_io { cli.run } + + json_data = JSON.parse(File.read(Dir.glob(File.join(tmpdir, "*.json")).first)) + args.executables.each_key do |name| + fib = json_data['raw_data'][name]['fib'] + assert_equal [1, 1], fib['bench_itrs_per_run'] + assert_equal 2, fib['warmup_itrs_per_run'].size + assert_equal 2, fib['bench'].size + end + end + end + + it 'flips the order of the executables every run' do + Dir.mktmpdir do |tmpdir| + args = create_args( + executables: { 'a' => [RbConfig.ruby], 'b' => [RbConfig.ruby] }, + name_filters: ['fib'], + out_path: tmpdir, + interleave: true, + runs: 2 + ) + + output = capture_io { BenchmarkRunner::CLI.new(args).run }.join + order = output.scan(/^Running benchmark "fib" \[(\w+)\]/).flatten + assert_equal %w[a b b a], order + end + end + + it 'drops a benchmark whose later run is killed by a signal' do + skip 'needs POSIX signals' if Gem.win_platform? + Dir.mktmpdir do |tmpdir| + counter = File.join(tmpdir, 'count') + wrapper = File.join(tmpdir, 'killed_on_second_run.rb') + File.write(wrapper, <<~RUBY) + if ARGV.any? { |arg| arg.end_with?('.rb') } + count = File.exist?(#{counter.inspect}) ? File.read(#{counter.inspect}).to_i + 1 : 1 + File.write(#{counter.inspect}, count.to_s) + Process.kill(:KILL, Process.pid) if count == 2 + end + exec(#{RbConfig.ruby.inspect}, *ARGV) + RUBY + args = create_args( + executables: { 'a' => [RbConfig.ruby], 'b' => [RbConfig.ruby, wrapper] }, + name_filters: ['fib'], + out_path: tmpdir, + interleave: true, + runs: 3 + ) + + output = capture_io { assert_raises(SystemExit) { BenchmarkRunner::CLI.new(args).run } }.join + json_data = JSON.parse(File.read(Dir.glob(File.join(tmpdir, "*.json")).first)) + assert_match(/^ b: fib$/, output) + assert_equal [1, 1, 1], json_data['raw_data']['a']['fib']['bench_itrs_per_run'] + refute json_data['raw_data']['b'].key?('fib') + assert_equal 2, output.scan(/^Running benchmark "fib" \[b\]/).size + end + end + + it 'refuses --runs with the Ractor harness' do + Dir.mktmpdir do |tmpdir| + args = create_args(name_filters: ['fib'], out_path: tmpdir, harness: 'ractor', harness_explicit: true, interleave: true, runs: 2) + + error = assert_raises(SystemExit) { capture_io { BenchmarkRunner::CLI.new(args).run } } + assert_match(/Ractor harness/, error.message) + end + end + + it 'refuses --pvalue with the callgrind harness' do + Dir.mktmpdir do |tmpdir| + args = create_args(name_filters: ['fib'], out_path: tmpdir, harness: 'callgrind', harness_explicit: true, interleave: true, runs: 2, pvalue: true) + + error = assert_raises(SystemExit) { capture_io { BenchmarkRunner::CLI.new(args).run } } + assert_match(/--pvalue does not support the callgrind harness/, error.message) + assert_empty Dir.glob(File.join(tmpdir, 'callgrind-*')) + end + end + it 'creates output directory if it does not exist' do Dir.mktmpdir do |parent_tmpdir| nested_dir = File.join(parent_tmpdir, 'nested', 'output', 'dir') diff --git a/test/benchmark_runner_test.rb b/test/benchmark_runner_test.rb index 580a8b92..cc179698 100644 --- a/test/benchmark_runner_test.rb +++ b/test/benchmark_runner_test.rb @@ -433,7 +433,7 @@ def git(dir, *args) ruby_descriptions, table, format, bench_failures, include_pvalue: true ) - assert_includes result, "- ***: p < 0.001, **: p < 0.01, *: p < 0.05 (Welch's t-test)" + assert_includes result, "- ***: 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)" end it 'prints the GC ratio and count tables and their legend when include_gc is true' do diff --git a/test/results_table_builder_test.rb b/test/results_table_builder_test.rb index c0ad30f3..1b5de94d 100644 --- a/test/results_table_builder_test.rb +++ b/test/results_table_builder_test.rb @@ -426,6 +426,7 @@ 'fib' => { 'warmup' => [0.1], 'bench' => [0.100, 0.101, 0.099, 0.1005, 0.0995, 0.1002, 0.0998, 0.1001, 0.0999, 0.1003], + 'bench_itrs_per_run' => [2, 2, 2, 2, 2], 'rss' => 1024 * 1024 * 10 } }, @@ -433,6 +434,7 @@ 'fib' => { 'warmup' => [0.05], 'bench' => [0.050, 0.051, 0.049, 0.0505, 0.0495, 0.0502, 0.0498, 0.0501, 0.0499, 0.0503], + 'bench_itrs_per_run' => [2, 2, 2, 2, 2], 'rss' => 1024 * 1024 * 12 } } @@ -520,6 +522,7 @@ 'fib' => { 'warmup' => [0.1], 'bench' => [0.100, 0.101, 0.099], + 'bench_itrs_per_run' => [1, 1, 1], 'rss' => 1024 * 1024 * 10 } }, @@ -527,6 +530,7 @@ 'fib' => { 'warmup' => [0.05], 'bench' => [0.050, 0.051, 0.049], + 'bench_itrs_per_run' => [1, 1, 1], 'rss' => 1024 * 1024 * 12 } } @@ -545,6 +549,100 @@ assert_match(/\(\*{1,3}\)/, table[1][ratio_col_idx]) end + it 'does not mark iterations of one process as significant' do + executable_names = ['ruby', 'ruby-yjit'] + bench_data = { + 'ruby' => { + 'fib' => { + 'warmup' => [0.1], + 'bench' => [0.100, 0.101, 0.099], + 'rss' => 1024 * 1024 * 10 + } + }, + 'ruby-yjit' => { + 'fib' => { + 'warmup' => [0.05], + 'bench' => [0.050, 0.051, 0.049], + 'rss' => 1024 * 1024 * 12 + } + } + } + + builder = ResultsTableBuilder.new( + executable_names: executable_names, + bench_data: bench_data, + include_pvalue: true + ) + + table, _format = builder.build + assert_includes table[0], 'p-value' + assert_includes table[0], 'sig' + ratio_col_idx = table[0].index('ruby/ruby-yjit') + assert_equal '2.000', table[1][ratio_col_idx] + assert_equal 'N/A', table[1][ratio_col_idx + 1] + end + + it 'tests the timing and GC ratios on the per-process means of --runs' do + bench_data = { + 'ruby-base' => { 'fib' => { 'warmup' => [0.1, 0.1], 'warmup_itrs_per_run' => [1, 1], + 'bench' => [1.0, 1.9, 2.0, 2.1], 'bench_itrs_per_run' => [1, 3], 'rss' => 1, + 'gc_marking_time_bench' => [20.0, 20.5, 21.0, 21.5], 'gc_sweeping_time_bench' => [10.0, 10.0, 10.0, 10.0] } }, + 'ruby-exp' => { 'fib' => { 'warmup' => [0.1, 0.1], 'warmup_itrs_per_run' => [1, 1], + 'bench' => [2.9, 3.1, 4.9, 5.1], 'bench_itrs_per_run' => [2, 2], 'rss' => 1, + 'gc_marking_time_bench' => [10.0, 10.0, 11.0, 11.0], 'gc_sweeping_time_bench' => [10.0, 10.0, 10.0, 10.0] } } + } + + table, _format, gc_tables = ResultsTableBuilder.new( + executable_names: ['ruby-base', 'ruby-exp'], bench_data: bench_data, include_pvalue: true + ).build + + ratio_col_idx = table[0].index('ruby-base/ruby-exp') + assert_equal '0.438', table[1][ratio_col_idx] + assert_equal '0.199', table[1][ratio_col_idx + 1] + ratios = gc_tables.first[:rows] + assert_equal '1.976 (**)', ratios[1][ratios[0].index('mark/iter')] + end + + it 'leaves out benchmarks without GC activity with --runs' do + gc = { 'gc_marking_time_bench' => [0.0, 0.0], 'gc_sweeping_time_bench' => [0.0, 0.0], + 'gc_count_bench' => [0, 0], 'gc_major_count_bench' => [0, 0], 'gc_minor_count_bench' => [0, 0] } + run = { 'warmup' => [0.1, 0.1], 'warmup_itrs_per_run' => [1, 1], 'bench' => [0.1, 0.1], 'bench_itrs_per_run' => [1, 1], 'rss' => 1 } + bench_data = { 'ruby-base' => { 'fib' => run.merge(gc) }, 'ruby-exp' => { 'fib' => run.merge(gc) } } + + _table, _format, gc_tables = ResultsTableBuilder.new(executable_names: ['ruby-base', 'ruby-exp'], bench_data: bench_data).build + + assert_nil gc_tables + end + + it 'does not mark GC ratios of one process as significant' do + bench_data = { + 'ruby-base' => { 'fib' => { 'warmup' => [0.1], 'bench' => [0.1, 0.1, 0.1], 'rss' => 1, + 'gc_marking_time_bench' => [20.0, 21.0, 19.0], 'gc_sweeping_time_bench' => [10.0, 10.0, 10.0] } }, + 'ruby-exp' => { 'fib' => { 'warmup' => [0.1], 'bench' => [0.1, 0.1, 0.1], 'rss' => 1, + 'gc_marking_time_bench' => [10.0, 11.0, 9.0], 'gc_sweeping_time_bench' => [10.0, 10.0, 10.0] } } + } + + _table, _format, gc_tables = ResultsTableBuilder.new( + executable_names: ['ruby-base', 'ruby-exp'], bench_data: bench_data, include_pvalue: true + ).build + + ratios = gc_tables.first[:rows] + assert_equal '2.000', ratios[1][ratios[0].index('mark/iter')] + end + + it 'averages the first iteration over the processes of --runs' do + bench_data = { + 'ruby' => { 'fib' => { 'warmup' => [0.3, 0.2, 0.1, 0.2], 'warmup_itrs_per_run' => [2, 2], + 'bench' => [0.1, 0.1], 'bench_itrs_per_run' => [1, 1], 'rss' => 1 } }, + 'ruby-yjit' => { 'fib' => { 'warmup' => [0.2, 0.1, 0.2, 0.1], 'warmup_itrs_per_run' => [2, 2], + 'bench' => [0.1, 0.1], 'bench_itrs_per_run' => [1, 1], 'rss' => 1 } } + } + + table, _format = ResultsTableBuilder.new(executable_names: ['ruby', 'ruby-yjit'], bench_data: bench_data).build + + assert_in_delta 1.0, table[1][table[0].index('ruby-yjit 1st itr')], 1e-9 + end + it 'handles only headline benchmarks' do executable_names = ['ruby'] bench_data = {