[ruby/benchmark] Adjust ljust Benchmark#bm with labels was not using the highest length among the labels to adjust the correct ljust. Instead of printing the result during the report generation, now it is waiting to print the result once it is generated.

Benchmark.bm { |x|
  x.item("aaaa") { 1 }
  x.item("aaaaaaaa") { 0 }
}

After

              user     system      total        real
aaaa      0.000005   0.000002   0.000007 (  0.000003)
aaaaaaaa  0.000001   0.000001   0.000002 (  0.000002)

Before

       user     system      total        real
aaaa  0.000005   0.000001   0.000006 (  0.000003)
aaaaaaaa  0.000002   0.000001   0.000003 (  0.000003)

https://github.com/ruby/benchmark/commit/3e74533ead
This commit is contained in:
Kaíque Kandy Koga 2022-08-08 14:53:05 -03:00 committed by Hiroshi SHIBATA
parent b56b70a373
commit 9523f53465
No known key found for this signature in database
GPG Key ID: F9CF13417264FAC2
2 changed files with 12 additions and 6 deletions

View File

@ -173,9 +173,15 @@ module Benchmark
label_width ||= 0 label_width ||= 0
label_width += 1 label_width += 1
format ||= FORMAT format ||= FORMAT
print ' '*label_width + caption unless caption.empty?
report = Report.new(label_width, format) report = Report.new(label_width, format)
results = yield(report) 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| Array === results and results.grep(Tms).each {|t|
print((labels.shift || t.label || "").ljust(label_width), t.format(format)) print((labels.shift || t.label || "").ljust(label_width), t.format(format))
} }
@ -380,16 +386,16 @@ module Benchmark
# formatting rules. # formatting rules.
# #
def item(label = "", *format, &blk) # :yield: def item(label = "", *format, &blk) # :yield:
print label.to_s.ljust(@width) w = label.to_s.length
@width = w if @width < w
@list << res = Benchmark.measure(label, &blk) @list << res = Benchmark.measure(label, &blk)
print res.format(@format, *format)
res res
end end
alias report item alias report item
# An array of Benchmark::Tms objects representing each item. # An array of Benchmark::Tms objects representing each item.
attr_reader :list attr_reader :width, :format, :list
end end