Class: RSpec::Matchers::BenchmarkComparison

Inherits:
Object
  • Object
show all
Defined in:
lib/should_be_faster.rb

Instance Method Summary collapse

Constructor Details

#initialize(rhs_code, options = {}) ⇒ BenchmarkComparison

Returns a new instance of BenchmarkComparison.



13
14
15
16
17
18
19
# File 'lib/should_be_faster.rb', line 13

def initialize(rhs_code, options={})
  @rhs_code = rhs_code
  @options  = options
  @options[:iterations] ||= 100
  @options[:factor]     ||= 1
  @options[:faster]       = @options[:faster]
end

Instance Method Details

#benchmark_comparisonObject



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
# File 'lib/should_be_faster.rb', line 21

def benchmark_comparison
  factor  = @options[:factor]
  iter    = @options[:iterations]
  matcher = @options[:matcher]
  faster  = @options[:faster]
  rhs     = _benchmark(@rhs_code, iter).real
  lhs     = nil

  matcher.match do |lhs_code|
    lhs = (_benchmark(lhs_code, iter).real * factor)
    if faster
      lhs < rhs
    else
      lhs > rhs
    end
  end

  matcher.instance_eval do
    failure_message_for_should do |actual|
      if faster
        "ran too slow: #{lhs / rhs}x, #{lhs - rhs}s"
      else
        "ran too fast: #{rhs / lhs}x, #{rhs - lhs}s"
      end
    end

    failure_message_for_should_not do |actual|
      if faster
        "ran too slow: #{rhs / lhs}x, #{rhs - lhs}s"
      else
        "ran too fast: #{lhs / rhs}x, #{lhs - rhs}s"
      end
    end

    description do
      if faster
        "be faster than #{rhs}"
      else
        "be slower than #{rhs}"
      end
    end
  end
end