Skip to content
Draft
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
58 changes: 48 additions & 10 deletions harness/callgrind.rb
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -20,13 +23,36 @@
"(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"

# Also exclude setup when the caller forgot --instr-atstart=no.
Valgrind.callgrind_stop_instrumentation

# Every client-requested dump goes to "<out file>.<part>", 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))
Expand All @@ -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
Expand All @@ -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}.<part>."
if ENV['RESULT_JSON_PATH']
return_results(warmup, bench, metrics: { "instructions" => { "bench" => instructions } }, primary_metric: "instructions")
end
end
9 changes: 7 additions & 2 deletions lib/benchmark_runner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
require 'json'
require 'rbconfig'
require 'shellwords'
require_relative 'metric'
require_relative 'table_formatter'
require_relative 'windows_pinning'

Expand Down Expand Up @@ -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

Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions lib/benchmark_runner/cli.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
8 changes: 7 additions & 1 deletion lib/benchmark_suite.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 9 additions & 7 deletions lib/graph_renderer.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require_relative '../misc/stats'
require_relative 'metric'
require 'json'
begin
require 'gruff'
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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
Expand Down
77 changes: 77 additions & 0 deletions lib/metric.rb
Original file line number Diff line number Diff line change
@@ -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
36 changes: 14 additions & 22 deletions lib/results_table_builder.rb
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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?
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading