Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
Benchmark#benchmark
# File tmp/rubies/ruby-3.4.1/lib/benchmark.rb, line 170
def benchmark(caption = "", label_width = nil, format = nil, *labels) # :yield: report
sync = $stdout.sync
$stdout.sync = true
label_width ||= 0
label_width += 1
format ||= FORMAT
report = Report.new(label_width, format)
results = yield(report)
print " " * report.width + caption unless caption.empty?
report.list.each { |i|
print i.label.to_s.ljust(report.width)
print i.format(report.format, *format)
}
Array === results and results.grep(Tms).each {|t|
print((labels.shift || t.label || "").ljust(label_width), t.format(format))
}
report.list
ensure
$stdout.sync = sync unless sync.nil?
end
Invokes the block with a Benchmark::Report object, which may be used to collect and report on the results of individual benchmark tests. Reserves label_width leading spaces for labels on each line. Prints caption at the top of the report, and uses format to format each line. (Note: caption must contain a terminating newline character, see the default Benchmark::Tms::CAPTION for an example.)
Returns an array of Benchmark::Tms objects.
If the block returns an array of Benchmark::Tms objects, these will be used to format additional lines of output. If labels parameter are given, these are used to label these extra lines.
Note: Other methods provide a simpler interface to this one, and are suitable for nearly all benchmarking requirements. See the examples in Benchmark, and the bm and bmbm methods.
Example:
require 'benchmark' include Benchmark # we need the CAPTION and FORMAT constants n = 5000000 Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| tf = x.report("for:") { for i in 1..n; a = "1"; end } tt = x.report("times:") { n.times do ; a = "1"; end } tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } [tf+tt+tu, (tf+tt+tu)/3] end
Generates:
user system total real for: 0.970000 0.000000 0.970000 ( 0.970493) times: 0.990000 0.000000 0.990000 ( 0.989542) upto: 0.970000 0.000000 0.970000 ( 0.972854) >total: 2.930000 0.000000 2.930000 ( 2.932889) >avg: 0.976667 0.000000 0.976667 ( 0.977630)