From 3e74533ead175bc32cf55075b32348f9d9c698b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ka=C3=ADque=20Kandy=20Koga?= Date: Mon, 8 Aug 2022 14:53:05 -0300 Subject: [PATCH] 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) --- lib/benchmark.rb | 14 ++++++++++---- test/benchmark/test_benchmark.rb | 4 ++-- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/lib/benchmark.rb b/lib/benchmark.rb index 79c782e..96f7db7 100644 --- a/lib/benchmark.rb +++ b/lib/benchmark.rb @@ -171,9 +171,15 @@ def benchmark(caption = "", label_width = nil, format = nil, *labels) # :yield: label_width ||= 0 label_width += 1 format ||= FORMAT - print ' '*label_width + caption unless caption.empty? 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)) } @@ -374,16 +380,16 @@ def initialize(width = 0, format = nil) # formatting rules. # 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) - print res.format(@format, *format) res end alias report item # An array of Benchmark::Tms objects representing each item. - attr_reader :list + attr_reader :width, :format, :list end diff --git a/test/benchmark/test_benchmark.rb b/test/benchmark/test_benchmark.rb index ddd4a59..2e0c47a 100644 --- a/test/benchmark/test_benchmark.rb +++ b/test/benchmark/test_benchmark.rb @@ -65,9 +65,9 @@ def test_tms_wont_modify_the_format_String_given def test_benchmark_does_not_print_any_space_if_the_given_caption_is_empty assert_equal(<<-BENCH, capture_bench_output(:benchmark)) -first --time-- --time-- --time-- ( --time--) +first --time-- --time-- --time-- ( --time--) second --time-- --time-- --time-- ( --time--) -third --time-- --time-- --time-- ( --time--) +third --time-- --time-- --time-- ( --time--) BENCH end