Class: Pandemic::RequestsPerSecond

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

Instance Method Summary collapse

Constructor Details

#initialize(sample_size = 10) ⇒ RequestsPerSecond

Returns a new instance of RequestsPerSecond.



3
4
5
6
# File 'lib/pandemic/requests_per_second.rb', line 3

def initialize(sample_size = 10)
  @hits = Array.new(sample_size + 2)
  @last_hit_at = nil
end

Instance Method Details

#hit(now = Time.now.to_i) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/pandemic/requests_per_second.rb', line 8

def hit(now = Time.now.to_i)
  key = now % @hits.size
  if @hits[key].nil? || @hits[key][0] != now
    @hits[key] = [now, 0]
  end
  @hits[key][1] += 1
  @last_hit_at = now
end

#rps(now = Time.now.to_i) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/pandemic/requests_per_second.rb', line 17

def rps(now = Time.now.to_i)
  return 0 if @last_hit_at.nil?
  entries_to_go_back = @hits.size - (now - @last_hit_at) - 2
  return 0 if entries_to_go_back <= 0
  sum = 0
  entries_to_go_back.times do |i|
    now -= 1 
    if @hits[now % @hits.size] && @hits[now % @hits.size][0] == now
      sum += @hits[now % @hits.size][1] 
    end
  end
  return sum.to_f / (@hits.size - 2)
end