File: comparison_formatter.rb

package info (click to toggle)
ruby-benchmark-memory 0.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 300 kB
  • sloc: ruby: 1,121; makefile: 7; sh: 4
file content (72 lines) | stat: -rw-r--r-- 1,976 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# frozen_string_literal: true

require 'benchmark/memory/helpers'
require 'benchmark/memory/job/io_output/metric_formatter'

module Benchmark
  module Memory
    class Job
      class IOOutput
        # Format a comparison for use with the IOOutput.
        class ComparisonFormatter
          include Helpers

          # Instantiate a formatter to output an comparison into an IO.
          #
          # @param comparison [Report::Comparison] The comparison to format.
          def initialize(comparison)
            @comparison = comparison
          end

          # @return [Report::Comparison] The comparison to format.
          attr_reader :comparison

          # Format comparison to a string to put on the output.
          #
          # @return [String]
          def to_s
            return '' unless comparison.possible?

            output = StringIO.new
            best, *rest = comparison.entries
            rest = Array(rest)

            add_best_summary(best, output)

            rest.each do |entry|
              add_comparison(entry, best, output)
            end

            output.string
          end

          private

          def add_best_summary(best, output)
            output << summary_message("%20s: %10i %s\n", best)
          end

          def add_comparison(entry, best, output)
            output << summary_message('%20s: %10i %s - ', entry)
            output << comparison_between(entry, best)
            output << "\n"
          end

          def comparison_between(entry, best)
            ratio = entry.compared_metric(comparison).to_f / best.compared_metric(comparison)

            if ratio.abs > 1
              format('%<ratio>.2fx more', ratio: ratio)
            else
              'same'
            end
          end

          def summary_message(message, entry)
            format(message, entry.label, entry.compared_metric(comparison), comparison.value)
          end
        end
      end
    end
  end
end