diff --git a/lib/benchmark/compare.rb b/lib/benchmark/compare.rb index 51f9952..dbfdffd 100644 --- a/lib/benchmark/compare.rb +++ b/lib/benchmark/compare.rb @@ -56,51 +56,49 @@ module Compare def compare(*entries, order: :fastest) return if entries.size < 2 - case order - when :baseline - baseline = entries.shift - sorted = entries.sort_by{ |e| e.stats.central_tendency }.reverse - when :fastest - sorted = entries.sort_by{ |e| e.stats.central_tendency }.reverse - baseline = sorted.shift - else - raise ArgumentError, "Unknwon order: #{order.inspect}" - end - - $stdout.puts "\nComparison:" + sorted, baseline = sort_and_find_baseline(entries, order) - $stdout.printf "%20s: %10.1f i/s\n", baseline.label.to_s, baseline.stats.central_tendency + puts "\nComparison:" + printf "%20s: %10.1f i/s\n", baseline.label.to_s, baseline.stats.central_tendency sorted.each do |report| name = report.label.to_s + printf "%20s: %10.1f i/s - ", name, report.stats.central_tendency - $stdout.printf "%20s: %10.1f i/s - ", name, report.stats.central_tendency + report_speedup, report_error = report.stats.compare_speed(baseline.stats) - if report.stats.overlaps?(baseline.stats) - $stdout.print "same-ish: difference falls within error" - elsif report.stats.central_tendency > baseline.stats.central_tendency - speedup, error = report.stats.speedup(baseline.stats) - $stdout.printf "%.2fx ", speedup - if error - $stdout.printf " (± %.2f)", error - end - $stdout.print " faster" + if report_error + printf "%.2fx (± %.2f) %s", report_speedup.abs, report_error, report_speedup > 0 ? "faster" : "slower" + elsif report_speedup.abs < 1e-9 + print "same-ish: difference falls within error" else - slowdown, error = report.stats.slowdown(baseline.stats) - $stdout.printf "%.2fx ", slowdown - if error - $stdout.printf " (± %.2f)", error - end - $stdout.print " slower" + printf "%.2fx %s", report_speedup.abs, report_speedup > 0 ? "faster" : "slower" end - $stdout.puts + puts end - footer = baseline.stats.footer - $stdout.puts footer.rjust(40) if footer + if (footer = baseline.stats.footer) + puts footer.rjust(40) + end - $stdout.puts + puts + end + + private + + def sort_and_find_baseline(entries, order) + case order + when :baseline + baseline = entries.shift + sorted = entries.sort_by { |e| e.stats.central_tendency }.reverse + when :fastest + sorted = entries.sort_by { |e| e.stats.central_tendency }.reverse + baseline = sorted.shift + else + raise ArgumentError, "Unknown order: #{order.inspect}" + end + [sorted, baseline] end end