diff --git a/harness/callgrind.rb b/harness/callgrind.rb index d860e81c..4861cef9 100644 --- a/harness/callgrind.rb +++ b/harness/callgrind.rb @@ -1,10 +1,13 @@ # frozen_string_literal: true -# Profile only the measured iterations with Callgrind (not setup or warmup). +# Profile only the measured iterations with Callgrind (not setup or warmup), +# and report each iteration's instruction count (Ir) alongside its time. # Usage: # WARMUP_ITRS=10 MIN_BENCH_ITRS=1 HARNESS=callgrind \ # valgrind --tool=callgrind --instr-atstart=no ruby benchmarks/fib.rb -# Use --callgrind-out-file=/absolute/path/callgrind.out.%p to choose the output. +# To choose the output, set VALGRIND_OPTS=--callgrind-out-file=/path/callgrind.out.%p +# rather than passing the flag: the harness reads each iteration's dump back, +# and Valgrind hides its command line (but not its environment) from the program. require_relative "../lib/harness" require_relative "../lib/harness/extra" @@ -20,6 +23,13 @@ "(e.g. ./run_benchmarks.rb --harness=callgrind)" end +# The last occurrence wins, as in Valgrind. Like Callgrind, resolve relative +# paths (including the default) against the startup directory, which this is +# loaded in before benchmark setup can chdir. +CALLGRIND_OUT_FILE = File.expand_path( + ENV.fetch("VALGRIND_OPTS", "")[/.*--callgrind-out-file=(\S+)/, 1] || "callgrind.out.%p" +).gsub("%p", Process.pid.to_s) + # Load before benchmark Bundler setup can hide globally installed gems. ensure_global_gem("valgrind") require "valgrind" @@ -27,6 +37,22 @@ # Also exclude setup when the caller forgot --instr-atstart=no. Valgrind.callgrind_stop_instrumentation +# Every client-requested dump goes to ".", with parts numbered +# from 1 within the process. The file is complete when the request returns. +def callgrind_dump_ir(description) + $callgrind_dump_part = ($callgrind_dump_part || 0) + 1 + Valgrind.callgrind_dump_stats(description) + # `summary:` can be garbage when instrumentation starts mid-call; `totals:` + # is reliable. Ir is the first event. + path = "#{CALLGRIND_OUT_FILE}.#{$callgrind_dump_part}" + unless File.exist?(path) + raise "callgrind dump not found at #{path}; pass --callgrind-out-file via VALGRIND_OPTS, not on the command line" + end + totals = File.binread(path)[/^totals: (\d+)/, 1] + raise "no totals in callgrind dump #{path}" unless totals + Integer(totals) +end + def run_benchmark(num_itrs_hint, **, &block) warmup_itrs = Integer(ENV.fetch('WARMUP_ITRS', 10)) bench_itrs = Integer(ENV.fetch('MIN_BENCH_ITRS', num_itrs_hint)) @@ -35,6 +61,7 @@ def run_benchmark(num_itrs_hint, **, &block) warmup = [] bench = [] + instructions = [] Valgrind.callgrind_stop_instrumentation warmup_itrs.times do start = get_time @@ -43,19 +70,30 @@ def run_benchmark(num_itrs_hint, **, &block) end begin + # Switching instrumentation discards every translation, so do it once and + # zero the counters before each iteration instead. Each dump then holds + # one iteration (plus the few instructions of the client requests). Valgrind.callgrind_start_instrumentation - Valgrind.callgrind_zero_stats - bench_itrs.times do + + bench_itrs.times do |i| start = get_time - block.call - bench << get_time - start + Valgrind.callgrind_zero_stats + begin + block.call + ensure + # Preserve a partial profile on failure. + elapsed = get_time - start + ir = callgrind_dump_ir("#{benchmark_name} itr #{i}") + end + bench << elapsed + instructions << ir end ensure - # Preserve a partial profile on failure, but never leave instrumentation on. Valgrind.callgrind_stop_instrumentation - Valgrind.callgrind_dump_stats(benchmark_name) end - puts "Callgrind stats dumped for #{benchmark_name} (output controlled by --callgrind-out-file)." - return_results(warmup, bench) if ENV['RESULT_JSON_PATH'] + puts "Callgrind stats dumped for #{benchmark_name} to #{CALLGRIND_OUT_FILE}.." + if ENV['RESULT_JSON_PATH'] + return_results(warmup, bench, metrics: { "instructions" => { "bench" => instructions } }, primary_metric: "instructions") + end end diff --git a/lib/benchmark_runner.rb b/lib/benchmark_runner.rb index 43c427ff..57d5d3df 100644 --- a/lib/benchmark_runner.rb +++ b/lib/benchmark_runner.rb @@ -4,6 +4,7 @@ require 'json' require 'rbconfig' require 'shellwords' +require_relative 'metric' require_relative 'table_formatter' require_relative 'windows_pinning' @@ -60,6 +61,7 @@ def write_csv(output_path, ruby_descriptions, table) end # Build output text string with metadata, table, and legend + # Each section may name the metric its table compares (default: time). def build_output_text(ruby_descriptions, table, format, bench_failures, include_rss: false, include_gc: false, include_pvalue: false, gc_tables: nil, memory_tables: nil, sections: nil, ruby_bench_revision: nil) base_name, *other_names = ruby_descriptions.keys @@ -84,10 +86,13 @@ def build_output_text(ruby_descriptions, table, format, bench_failures, include_ end unless other_names.empty? + metrics = sections.map { |section| section[:metric] || Metric::TIME }.uniq + noun = metrics.map(&:noun).join(" or ") + better = metrics.map(&:better).join(" or ") output_str << "Legend:\n" other_names.each do |name| - output_str << "- #{name} 1st itr: ratio of #{base_name}/#{name} time for the first iteration.\n" - output_str << "- #{base_name}/#{name}: ratio of #{base_name}/#{name} time. Higher is better for #{name}. Above 1 represents a speedup.\n" + output_str << "- #{name} 1st itr: ratio of #{base_name}/#{name} #{noun} for the first iteration.\n" + output_str << "- #{base_name}/#{name}: ratio of #{base_name}/#{name} #{noun}. Higher is better for #{name}. Above 1 represents #{better}.\n" if include_rss output_str << "- RSS #{base_name}/#{name}: ratio of #{base_name}/#{name} RSS. Higher is better for #{name}. Above 1 means lower memory usage.\n" end diff --git a/lib/benchmark_runner/cli.rb b/lib/benchmark_runner/cli.rb index bf210402..51f9a3c6 100644 --- a/lib/benchmark_runner/cli.rb +++ b/lib/benchmark_runner/cli.rb @@ -218,6 +218,7 @@ def build_output_section(executable_names, bench_data, bench_failures, harness, include_gc: builder.include_gc?, gc_tables: gc_tables, memory_tables: memory_tables, + metric: builder.metric, } if ResultsTableBuilder.ractor_gc_data?(section_data) section[:gc_scope] = 'ractor-local-workload' diff --git a/lib/benchmark_suite.rb b/lib/benchmark_suite.rb index 0ac3a780..beba389e 100644 --- a/lib/benchmark_suite.rb +++ b/lib/benchmark_suite.rb @@ -229,14 +229,20 @@ def run_single_benchmark(script_path, result_json_path, ruby, cmd_prefix, env, b # Keep output outside benchmark directories, which may chdir during setup. # The child PID makes profiles unique across benchmarks and Ruby configurations. + # The output file goes in VALGRIND_OPTS rather than on the command line + # because the harness reads each iteration's dump back, and Valgrind hides + # its command line (but not its environment) from the program. def callgrind_cmd(script_path) name = File.basename(script_path, '.rb') name = File.basename(File.dirname(script_path)) if name == 'benchmark' profile_dir = File.expand_path(out_path) + # Valgrind splits VALGRIND_OPTS on whitespace. + raise ArgumentError, "callgrind output path must not contain whitespace: #{profile_dir}" if profile_dir.match?(/\s/) FileUtils.mkdir_p(profile_dir) + valgrind_opts = [ENV["VALGRIND_OPTS"], "--callgrind-out-file=#{File.join(profile_dir, "callgrind-#{name}.out.%p")}"] [ + "env", "VALGRIND_OPTS=#{valgrind_opts.compact.join(" ")}", "valgrind", "--tool=callgrind", "--instr-atstart=no", - "--callgrind-out-file=#{File.join(profile_dir, "callgrind-#{name}.out.%p")}", ] end diff --git a/lib/graph_renderer.rb b/lib/graph_renderer.rb index 399d04fd..a10e6148 100644 --- a/lib/graph_renderer.rb +++ b/lib/graph_renderer.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative '../misc/stats' +require_relative 'metric' require 'json' begin require 'gruff' @@ -26,12 +27,13 @@ class GraphRenderer class << self def render(json_path, png_path, title_font_size: 16.0, legend_font_size: 12.0, marker_font_size: 10.0) ruby_descriptions, data, baseline, bench_names = load_benchmark_data(json_path) + metric = Metric.for(data.values.flat_map(&:values)) graph = Gruff::Bar.new(DEFAULT_WIDTH) - configure_graph(graph, ruby_descriptions, bench_names, title_font_size, legend_font_size, marker_font_size) + configure_graph(graph, metric, ruby_descriptions, bench_names, title_font_size, legend_font_size, marker_font_size) ruby_descriptions.each do |ruby, description| - speedups = calculate_speedups(data, baseline, ruby, bench_names) + speedups = calculate_speedups(metric, data, baseline, ruby, bench_names) graph.data "#{ruby}: #{description}", speedups end graph.write(png_path) @@ -50,8 +52,8 @@ def load_benchmark_data(json_path) [ruby_descriptions, data, baseline, bench_names] end - def configure_graph(graph, ruby_descriptions, bench_names, title_font_size, legend_font_size, marker_font_size) - graph.title = "Speedup ratio relative to #{ruby_descriptions.keys.first}" + def configure_graph(graph, metric, ruby_descriptions, bench_names, title_font_size, legend_font_size, marker_font_size) + graph.title = "#{metric.ratio_title} relative to #{ruby_descriptions.keys.first}" graph.title_font_size = title_font_size graph.theme = THEME graph.labels = bench_names.map.with_index { |bench, index| [index, bench] }.to_h @@ -62,10 +64,10 @@ def configure_graph(graph, ruby_descriptions, bench_names, title_font_size, lege graph.marker_font_size = marker_font_size end - def calculate_speedups(data, baseline, ruby, bench_names) + def calculate_speedups(metric, data, baseline, ruby, bench_names) bench_names.map { |bench| - baseline_times = data.fetch(baseline).fetch(bench).fetch("bench") - times = data.fetch(ruby).fetch(bench).fetch("bench") + baseline_times = metric.bench(data.fetch(baseline).fetch(bench)) + times = metric.bench(data.fetch(ruby).fetch(bench)) Stats.new(baseline_times).mean / Stats.new(times).mean } end diff --git a/lib/metric.rb b/lib/metric.rb new file mode 100644 index 00000000..0f62233c --- /dev/null +++ b/lib/metric.rb @@ -0,0 +1,77 @@ +# frozen_string_literal: true + +# A quantity measured once per benchmark iteration, and how to show and compare +# it. Results compare on wall time unless the harness reports another metric: +# +# return_results(warmup, bench, +# metrics: { "name" => { "warmup" => [...], "bench" => [...] } }, +# primary_metric: "name") +# +# with values in the metric's raw unit, one per iteration ("warmup" may be left +# out when warmup is not measured). Top-level "warmup" and "bench" stay wall time +# in seconds. Every metric is lower-is-better, so base/exp above 1 favors exp. +class Metric + attr_reader :name, :noun, :unit, :scale, :better, :ratio_title + + # unit and scale are for display: raw value * scale is shown in unit. better + # completes "Above 1 represents ..." and ratio_title names the graph. + def initialize(name, noun:, unit:, scale:, better:, ratio_title:) + @name = name + @noun = noun + @unit = unit + @scale = scale + @better = better + @ratio_title = ratio_title + end + + REGISTRY = {} + + def self.register(name, **options) + REGISTRY[name] = new(name, **options) + end + + # Metrics nobody registered still compare, shown in their raw unit. + def self.[](name) + REGISTRY.fetch(name) do + new(name, noun: name, unit: name, scale: 1, better: "a lower #{name}", ratio_title: "#{name} ratio") + end + end + + TIME = register("time", noun: "time", unit: "ms", scale: 1000.0, better: "a speedup", ratio_title: "Speedup ratio") + # Instructions executed (Ir), from harness/callgrind.rb. + register("instructions", noun: "instruction count", unit: "MIr", scale: 1e-6, + better: "fewer instructions", ratio_title: "Instruction count ratio") + + # The metric to compare results on: their primary metric when they all agree, + # otherwise wall time, which every result has. + def self.for(results) + names = results.map { |data| data['primary_metric'] || TIME.name }.uniq + names.size == 1 ? self[names.first] : TIME + end + + # Values per measured iteration, in display units. + def bench(data) + series(data, 'bench') + end + + # Values per warmup iteration, in display units, or nil if warmup was not measured. + def warmup(data) + series(data, 'warmup') + end + + # The first iteration's value: the first warmup iteration, or the first + # measured one when there was no warmup. nil if warmup was not measured. + def first_iteration(data) + warmup = warmup(data) + return nil if warmup.nil? + + warmup.first || bench(data).first + end + + private + + def series(data, key) + values = name == TIME.name ? data[key] : data.dig('metrics', name, key) + values&.map { |value| value * scale } + end +end diff --git a/lib/results_table_builder.rb b/lib/results_table_builder.rb index 6f48a09a..de643aeb 100644 --- a/lib/results_table_builder.rb +++ b/lib/results_table_builder.rb @@ -1,12 +1,12 @@ require_relative '../misc/stats' require_relative 'row_layout' +require_relative 'metric' require 'yaml' class ResultsTableBuilder - SECONDS_TO_MS = 1000.0 BYTES_TO_MIB = 1024.0 * 1024.0 - attr_reader :bench_names + attr_reader :bench_names, :metric def initialize(executable_names:, bench_data:, include_rss: false, include_pvalue: false, zjit_stats: [], row_layout: FlatRowLayout.new) @executable_names = executable_names @@ -20,6 +20,7 @@ def initialize(executable_names:, bench_data:, include_rss: false, include_pvalu @other_names = executable_names[1..] @row_layout = row_layout @bench_names = compute_bench_names + @metric = Metric.for(bench_data.values.flat_map(&:values).select { |d| d.is_a?(Hash) }) end def include_gc? @@ -55,7 +56,7 @@ def build_header header = ["bench", *@row_layout.extra_header_columns] @executable_names.each do |name| - header << "#{name} (ms)" + header << "#{name} (#{@metric.unit})" header << "RSS (MiB)" if @include_rss @zjit_stats.each { |stat| header << stat } end @@ -405,8 +406,8 @@ def include_gc_total_time? end def build_stat_cells(bench_name) - t0s = extract_first_iteration_times(bench_name) - times_no_warmup = extract_benchmark_times(bench_name) + t0s = extract_metric(bench_name) { |data| @metric.first_iteration(data) } + times_no_warmup = extract_metric(bench_name) { |data| @metric.bench(data) } rsss = extract_rss_values(bench_name) rss_series = @rss_has_samples ? extract_rss_series(bench_name) : nil @@ -432,14 +433,14 @@ def build_stat_cells(bench_name) end def build_base_columns(row, base_t, base_rss, zjit_stat_values, exe_index) - row << format_time_with_stddev(base_t) + row << format_mean_with_stddev(base_t) row << base_rss if @include_rss zjit_stat_values.each { |_stat, values| row << format_stat(values[exe_index]) } end def build_comparison_columns(row, other_ts, other_rss_cells, zjit_stat_values) other_ts.each_with_index do |other_t, i| - row << format_time_with_stddev(other_t) + row << format_mean_with_stddev(other_t) row << other_rss_cells[i] if @include_rss zjit_stat_values.each { |_stat, values| row << format_stat(values[i + 1]) } end @@ -450,14 +451,14 @@ def format_stat(value) value.to_s.gsub(/(\d)(?=(\d{3})+(?!\d))/, '\1,') end - def format_time_with_stddev(values) + def format_mean_with_stddev(values) return "N/A" if values.nil? || values.empty? "%.1f ± %.1f%%" % [mean(values), stddev_percent(values)] end def build_ratio_columns(row, base_t0, other_t0s, base_t, other_ts) - ratio_1sts = other_t0s.map { |other_t0| base_t0 / other_t0 } - row.concat(ratio_1sts) + # Metrics without warmup values have no first iteration to compare. + row.concat(other_t0s.map { |other_t0| base_t0 / other_t0 if base_t0 && other_t0 }) other_ts.each do |other_t| pval = @include_pvalue ? Stats.welch_p_value(base_t, other_t) : nil @@ -615,17 +616,8 @@ def significance_level(pval) end end - 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 - end - end - - def extract_benchmark_times(bench_name) - @executable_names.map do |name| - bench_data_for(name, bench_name)['bench'].map { |v| v * SECONDS_TO_MS } - end + def extract_metric(bench_name) + @executable_names.map { |name| yield bench_data_for(name, bench_name) } end # Numeric RSS (MiB) per executable, used for the RSS ratio. When per-iteration @@ -657,7 +649,7 @@ def extract_rss_series(bench_name) def rss_cell(mean_value, series) return mean_value unless @rss_has_samples if series && !series.empty? - format_time_with_stddev(series) + format_mean_with_stddev(series) else "%.1f" % mean_value end diff --git a/lib/table_formatter.rb b/lib/table_formatter.rb index 87edc12b..54cbdb47 100644 --- a/lib/table_formatter.rb +++ b/lib/table_formatter.rb @@ -47,8 +47,9 @@ def build_formatted_data_rows @data_rows.map { |row| apply_format(row) } end + # nil marks a value that was not measured. def apply_format(row) - @format.zip(row).map { |fmt, data| fmt % data } + @format.zip(row).map { |fmt, data| data.nil? ? FAILURE_PLACEHOLDER : fmt % data } end def calculate_column_widths(rows) diff --git a/test/benchmark_runner_test.rb b/test/benchmark_runner_test.rb index 580a8b92..ccec5bf9 100644 --- a/test/benchmark_runner_test.rb +++ b/test/benchmark_runner_test.rb @@ -417,6 +417,19 @@ def git(dir, *args) refute_includes result, "p < 0.001" end + it 'describes the metric each section compares' do + require_relative '../lib/metric' + metric = Metric.new('test_ir', noun: 'instruction count', unit: 'MIr', scale: 1e-6, + better: 'fewer instructions', ratio_title: 'Instruction count ratio') + table = [['bench', 'base (MIr)', 'exp (MIr)', 'base/exp'], ['fib', '2.0', '1.0', '2.0']] + sections = [{ table: table, format: ['%s'] * 4, failures: {}, metric: metric }] + + result = BenchmarkRunner.build_output_text({ 'base' => 'ruby a', 'exp' => 'ruby b' }, nil, nil, {}, sections: sections) + + assert_includes result, '- exp 1st itr: ratio of base/exp instruction count for the first iteration.' + assert_includes result, '- base/exp: ratio of base/exp instruction count. Higher is better for exp. Above 1 represents fewer instructions.' + end + it 'includes p-value legend when include_pvalue is true' do ruby_descriptions = { 'ruby-base' => 'ruby 3.3.0', diff --git a/test/benchmark_suite_test.rb b/test/benchmark_suite_test.rb index 3786b202..728aa3e3 100644 --- a/test/benchmark_suite_test.rb +++ b/test/benchmark_suite_test.rb @@ -735,10 +735,10 @@ def capture_benchmark_command(harness, script: 'benchmarks/simple.rb', status: 0 it 'wraps Ruby after CPU pinning and preserves Ruby flags and the harness' do command, env, result = capture_benchmark_command('callgrind') - assert_equal ['taskset', '-c', '2', 'valgrind', '--tool=callgrind', '--instr-atstart=no'], command.take(6) - assert_equal "--callgrind-out-file=#{@out_path}/callgrind-simple.out.%p", command[6] + assert_equal ['taskset', '-c', '2', 'env', "VALGRIND_OPTS=--callgrind-out-file=#{@out_path}/callgrind-simple.out.%p", + 'valgrind', '--tool=callgrind', '--instr-atstart=no'], command.take(8) assert_equal ['/path with spaces/ruby', '--yjit', '-r', File.join(BenchmarkSuite::HARNESS_DIR, 'callgrind'), - File.expand_path('benchmarks/simple.rb')], command.drop(7) + File.expand_path('benchmarks/simple.rb')], command.drop(8) assert_equal 'callgrind', env['HARNESS'] assert_equal command, Shellwords.split(result[:command]) assert_nil ENV['RESULT_JSON_PATH'] @@ -746,7 +746,15 @@ def capture_benchmark_command(harness, script: 'benchmarks/simple.rb', status: 0 it 'uses the benchmark directory name for macrobenchmarks' do command, = capture_benchmark_command('callgrind', script: 'benchmarks/railsbench/benchmark.rb') - assert_equal "--callgrind-out-file=#{@out_path}/callgrind-railsbench.out.%p", command[6] + assert_equal "VALGRIND_OPTS=--callgrind-out-file=#{@out_path}/callgrind-railsbench.out.%p", command[4] + end + + it 'keeps existing VALGRIND_OPTS' do + ENV['VALGRIND_OPTS'] = '--dump-instr=yes' + command, = capture_benchmark_command('callgrind') + assert_equal "VALGRIND_OPTS=--dump-instr=yes --callgrind-out-file=#{@out_path}/callgrind-simple.out.%p", command[4] + ensure + ENV.delete('VALGRIND_OPTS') end it 'does not wrap other harnesses' do diff --git a/test/callgrind_harness_test.rb b/test/callgrind_harness_test.rb index d60a8600..bffabeee 100644 --- a/test/callgrind_harness_test.rb +++ b/test/callgrind_harness_test.rb @@ -32,12 +32,26 @@ def run_harness(env = {}, fail_at: nil) # Fake a global gem so tests do not install a native extension. gem_lib = File.join(dir, 'gems', 'lib') FileUtils.mkdir_p(gem_lib) + # Model Callgrind's counters: client requests cost 1 Ir and the workload + # charges its own, but only while instrumented. Dumps write the real + # "." layout (as resolved by the harness) and reset the + # counter. File.write(File.join(gem_lib, 'valgrind.rb'), <<~RUBY) module Valgrind - def self.callgrind_stop_instrumentation; $events << 'stop'; end - def self.callgrind_start_instrumentation; $events << 'start'; end - def self.callgrind_zero_stats; $events << 'zero'; end - def self.callgrind_dump_stats(name); $events << "dump:" + name; end + @instrumented = true + @ir = 0 + @part = 0 + def self.charge(ir); @ir += ir if @instrumented; end + def self.callgrind_stop_instrumentation; @instrumented = false; $events << 'stop'; end + def self.callgrind_start_instrumentation; @instrumented = true; charge(1); $events << 'start'; end + def self.callgrind_zero_stats; @ir = 0; charge(1); $events << 'zero'; end + def self.callgrind_dump_stats(name) + charge(1) + $events << "dump:" + name + @part += 1 + File.write(ENV.fetch('FAKE_DUMP_PREFIX', CALLGRIND_OUT_FILE) + ".\#{@part}", "events: Ir\nsummary: 1\ntotals: \#{@ir}\n") + @ir = 0 + end end RUBY script = fake_platform + <<~RUBY @@ -49,14 +63,16 @@ def ensure_global_gem(name) $LOAD_PATH << #{gem_lib.inspect} end require #{File.join(ROOT, 'harness/callgrind').inspect} - def return_results(warmup, bench) - $events << ['results', warmup.size, bench.size] + def return_results(warmup, bench, metrics:, primary_metric:) + raise 'wrong metric' unless primary_metric == 'instructions' && metrics.keys == ['instructions'] + $events << ['results', warmup.size, bench.size, metrics['instructions']['bench']] end calls = 0 begin run_benchmark(3, ignored_keyword: true) do calls += 1 $events << 'work' + Valgrind.charge(calls * 10) raise 'workload failed' if calls == #{fail_at.inspect} end rescue => e @@ -67,27 +83,34 @@ def return_results(warmup, bench) clean_env = { 'RUBYOPT' => nil, 'BUNDLE_GEMFILE' => nil, 'BUNDLER_SETUP' => nil, 'WARMUP_ITRS' => '2', 'MIN_BENCH_ITRS' => nil, - 'RESULT_JSON_PATH' => File.join(dir, 'results.json') - }.merge(env) - out, err, status = Open3.capture3(clean_env, RbConfig.ruby, '-I', dir, '-e', script, chdir: ROOT) + 'RESULT_JSON_PATH' => File.join(dir, 'results.json'), + 'VALGRIND_OPTS' => nil, 'FAKE_DUMP_PREFIX' => nil + }.merge(env.transform_values { |v| v&.gsub('DIR', dir) }) + out, err, status = Open3.capture3(clean_env, RbConfig.ruby, '-I', dir, '-e', script, chdir: dir) assert status.success?, "#{out}\n#{err}" + yield dir if block_given? JSON.parse(out.lines.last) end end + def measured(i) + ['zero', 'work', "dump:-e itr #{i}"] + end + def test_profiles_hint_iterations_after_warmup - assert_equal ['stop', 'stop', 'work', 'work', 'start', 'zero', - 'work', 'work', 'work', 'stop', 'dump:-e', ['results', 2, 3]], run_harness + assert_equal ['stop', 'stop', 'work', 'work', 'start', + *measured(0), *measured(1), *measured(2), + 'stop', ['results', 2, 3, [32, 42, 52]]], run_harness end def test_iteration_overrides_and_zero_warmup - assert_equal ['stop', 'stop', 'start', 'zero', 'work', 'stop', 'dump:-e', ['results', 0, 1]], + assert_equal ['stop', 'stop', 'start', *measured(0), 'stop', ['results', 0, 1, [12]]], run_harness({ 'WARMUP_ITRS' => '0', 'MIN_BENCH_ITRS' => '1' }) end - def test_failure_stops_and_dumps_without_results - assert_equal ['stop', 'stop', 'work', 'work', 'start', 'zero', 'work', - 'stop', 'dump:-e', 'workload failed'], run_harness({}, fail_at: 3) + def test_failure_stops_collecting_and_dumps_without_results + assert_equal ['stop', 'stop', 'work', 'work', 'start', *measured(0), + 'stop', 'workload failed'], run_harness({}, fail_at: 3) end def test_warmup_failure_never_starts_profiling @@ -106,6 +129,25 @@ def test_direct_execution_does_not_write_results refute run_harness({ 'RESULT_JSON_PATH' => nil }).any? { |event| event.is_a?(Array) } end + def test_dumps_to_callgrind_default_in_startup_directory + run_harness({ 'MIN_BENCH_ITRS' => '1' }) do |dir| + assert_equal 1, Dir.glob(File.join(dir, 'callgrind.out.*.1')).size + end + end + + def test_dumps_to_last_out_file_in_valgrind_opts + opts = '--callgrind-out-file=DIR/ignored.%p --dump-instr=yes --callgrind-out-file=DIR/last.%p' + run_harness({ 'MIN_BENCH_ITRS' => '1', 'VALGRIND_OPTS' => opts }) do |dir| + assert_equal 1, Dir.glob(File.join(dir, 'last.*.1')).size + assert_empty Dir.glob(File.join(dir, 'ignored.*')) + end + end + + def test_explains_missing_dump + events = run_harness({ 'FAKE_DUMP_PREFIX' => 'DIR/elsewhere' }) + assert_match(/dump not found .*pass --callgrind-out-file via VALGRIND_OPTS/, events.last) + end + def test_rejects_non_linux _, err, status = load_harness(host_os: 'darwin24') refute status.success? diff --git a/test/graph_renderer_test.rb b/test/graph_renderer_test.rb index 90f5f2a9..a77af118 100644 --- a/test/graph_renderer_test.rb +++ b/test/graph_renderer_test.rb @@ -81,4 +81,12 @@ end end end + + it 'plots ratios of the primary metric' do + data = { + 'a' => { 'b1' => { 'bench' => [1.0], 'metrics' => { 'cycles' => { 'bench' => [40] } }, 'primary_metric' => 'cycles' } }, + 'b' => { 'b1' => { 'bench' => [1.0], 'metrics' => { 'cycles' => { 'bench' => [20] } }, 'primary_metric' => 'cycles' } }, + } + assert_equal [2.0], GraphRenderer.send(:calculate_speedups, Metric['cycles'], data, 'a', 'b', ['b1']) + end end diff --git a/test/metric_test.rb b/test/metric_test.rb new file mode 100644 index 00000000..badffdb1 --- /dev/null +++ b/test/metric_test.rb @@ -0,0 +1,50 @@ +require_relative 'test_helper' +require_relative '../lib/metric' + +describe Metric do + before do + @ir = Metric.register('test_ir', noun: 'instruction count', unit: 'MIr', scale: 1e-6, + better: 'fewer instructions', ratio_title: 'Instruction count ratio') + end + + after do + Metric::REGISTRY.delete('test_ir') + end + + it 'reads wall time from the top-level series in milliseconds' do + data = { 'warmup' => [0.5], 'bench' => [0.1, 0.2] } + assert_equal [500.0], Metric::TIME.warmup(data) + assert_equal [100.0, 200.0], Metric::TIME.bench(data) + end + + it 'reads other metrics from the metrics hash in display units' do + data = { 'bench' => [1.0], 'metrics' => { 'test_ir' => { 'bench' => [2_000_000, 3_000_000] } } } + assert_equal [2.0, 3.0], @ir.bench(data) + assert_nil @ir.warmup(data) + end + + it 'takes the first iteration from warmup, falling back to bench only when warmup is empty' do + assert_equal 500.0, Metric::TIME.first_iteration({ 'warmup' => [0.5], 'bench' => [0.1] }) + assert_equal 100.0, Metric::TIME.first_iteration({ 'warmup' => [], 'bench' => [0.1] }) + assert_nil @ir.first_iteration({ 'metrics' => { 'test_ir' => { 'bench' => [1] } } }) + end + + it 'compares on the primary metric only when every result agrees' do + ir = { 'primary_metric' => 'test_ir' } + assert_same @ir, Metric.for([ir, ir]) + assert_same Metric::TIME, Metric.for([ir, {}]) + assert_same Metric::TIME, Metric.for([]) + end + + it 'shows callgrind instruction counts in millions' do + metric = Metric['instructions'] + assert_equal 'MIr', metric.unit + assert_equal [2.5], metric.bench({ 'metrics' => { 'instructions' => { 'bench' => [2_500_000] } } }) + end + + it 'shows unregistered metrics in their raw unit' do + metric = Metric['cycles'] + assert_equal 'cycles', metric.unit + assert_equal [7], metric.bench({ 'metrics' => { 'cycles' => { 'bench' => [7] } } }) + end +end diff --git a/test/ractor_breakdown_test.rb b/test/ractor_breakdown_test.rb index 38397ce9..abf122dc 100644 --- a/test/ractor_breakdown_test.rb +++ b/test/ractor_breakdown_test.rb @@ -229,6 +229,18 @@ def child_blob(count, warmup:, bench:, rss:, zjit_calls:) refute r0.key?('results_by_ractors') end + it 'keeps each count\'s own metric series' do + blobs = [0, 2].to_h do |count| + blob = child_blob(count, warmup: [1.0], bench: [1.0], rss: 100, zjit_calls: 1) + [count, blob.merge('metrics' => { 'ir' => { 'bench' => [count * 10] } }, 'primary_metric' => 'ir')] + end + exe = RactorBreakdown.expand({ 'ruby' => { 'r' => RactorBreakdown.merge(blobs) } }).bench_data['ruby'] + + assert_equal({ 'ir' => { 'bench' => [0] } }, exe["r\x000"]['metrics']) + assert_equal({ 'ir' => { 'bench' => [20] } }, exe["r\x002"]['metrics']) + assert_equal 'ir', exe["r\x002"]['primary_metric'] + end + it 'keeps scenario memory data keyed by count and the base RSS per process' do scenario_blob = lambda do |count, retained| { diff --git a/test/results_table_builder_test.rb b/test/results_table_builder_test.rb index c0ad30f3..f5e4c14e 100644 --- a/test/results_table_builder_test.rb +++ b/test/results_table_builder_test.rb @@ -606,6 +606,68 @@ end end + describe 'metrics' do + before do + Metric.register('test_ir', noun: 'instruction count', unit: 'MIr', scale: 1e-6, + better: 'fewer instructions', ratio_title: 'Instruction count ratio') + end + + after do + Metric::REGISTRY.delete('test_ir') + end + + def ir_result(bench_ir, warmup_ir: nil) + ir = { 'bench' => bench_ir } + ir['warmup'] = warmup_ir if warmup_ir + { 'warmup' => [1.0], 'bench' => [1.0, 1.0], 'rss' => MIB, 'metrics' => { 'test_ir' => ir }, 'primary_metric' => 'test_ir' } + end + + it 'compares on the primary metric, with no first-iteration ratio without warmup values' do + builder = ResultsTableBuilder.new( + executable_names: ['base', 'exp'], + bench_data: { + 'base' => { 'fib' => ir_result([200_000_000, 200_000_000]) }, + 'exp' => { 'fib' => ir_result([100_000_000, 100_000_000]) }, + } + ) + table, format = builder.build + + assert_equal 'test_ir', builder.metric.name + assert_equal ['bench', 'base (MIr)', 'exp (MIr)', 'exp 1st itr', 'base/exp'], table[0] + assert_equal ['fib', '200.0 ± 0.0%', '100.0 ± 0.0%', nil, '2.000'], table[1] + assert_equal 5, format.size + end + + it 'compares first iterations when the metric records warmup' do + builder = ResultsTableBuilder.new( + executable_names: ['base', 'exp'], + bench_data: { + 'base' => { 'fib' => ir_result([2_000_000], warmup_ir: [9_000_000]) }, + 'exp' => { 'fib' => ir_result([1_000_000], warmup_ir: [3_000_000]) }, + } + ) + table, = builder.build + + assert_equal ['bench', 'base (MIr)', 'exp (MIr)', 'exp 1st itr', 'base/exp'], table[0] + assert_in_delta 3.0, table[1][3] + end + + it 'falls back to time when results disagree on the primary metric' do + builder = ResultsTableBuilder.new( + executable_names: ['base', 'exp'], + bench_data: { + 'base' => { 'fib' => ir_result([200_000_000]) }, + 'exp' => { 'fib' => { 'warmup' => [0.5], 'bench' => [0.5], 'rss' => MIB } }, + } + ) + table, = builder.build + + assert_same Metric::TIME, builder.metric + assert_equal ['bench', 'base (ms)', 'exp (ms)', 'exp 1st itr', 'base/exp'], table[0] + assert_equal '2.000', table[1][4] + end + end + describe 'scenario memory table' do # The mean and the max are offset from the median so the columns cannot be # confused for each other. diff --git a/test/table_formatter_test.rb b/test/table_formatter_test.rb index e49439e0..bb861c48 100644 --- a/test/table_formatter_test.rb +++ b/test/table_formatter_test.rb @@ -102,6 +102,12 @@ end end + it 'shows N/A for values that were not measured' do + table_data = [['bench', 'ratio'], ['fib', nil]] + result = TableFormatter.new(table_data, ['%s', '%.3f'], {}).to_s + assert_includes result.lines[2], 'N/A' + end + it 'applies format strings correctly' do table_data = [ ['bench', 'time'],