Module: RSpec::Benchmark::Formatter

Defined in:
lib/rspec/benchmark/formatter.rb

Constant Summary collapse

UNITS =
([""] + %w[k M B T Q]).freeze

Class Method Summary collapse

Class Method Details

.format_time(time) ⇒ String

Format time for easy matcher reporting

Parameters:

  • time (Float)

    the time to format

Returns:

  • (String)

    the human readable time value



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rspec/benchmark/formatter.rb', line 15

def format_time(time)
  if time >= 100.0
    "%.0f sec" % [time]
  elsif time >= 1.0
    "%.3g sec" % [time]
  elsif time >= 1e-3
    "%.3g ms" % [time * 1e3]
  elsif time >= 1e-6
    "%.3g μs" % [time * 1e6]
  else
    "%.3g ns" % [time * 1e9]
  end
end

.format_unit(number) ⇒ String

Format large numbers and replace thousands with a unit for increased readability

Parameters:

  • number (Numeric)

    the number to format

Returns:

  • (String)


41
42
43
44
45
46
47
# File 'lib/rspec/benchmark/formatter.rb', line 41

def format_unit(number)
  scale = (Math.log10(number) / 3).to_i
  scale = 0 if scale > 5
  suffix = UNITS[scale]

  "%.3g#{suffix}" % [number.to_f / (1000 ** scale)]
end