Class: Async::Container::Statistics::Rate
- Inherits:
-
Object
- Object
- Async::Container::Statistics::Rate
- Defined in:
- lib/async/container/statistics.rb
Overview
Tracks rate information over a sliding time window using a circular buffer.
Instance Attribute Summary collapse
-
#window ⇒ Object
readonly
The time window in seconds for rate calculations.
Instance Method Summary collapse
-
#add(value = 1, time: self.now) ⇒ Object
Add a value to the current time slot.
-
#initialize(window: 60) ⇒ Rate
constructor
Initialize the event rate counter.
-
#now ⇒ Object
Get the current time in seconds.
-
#per_minute(time: self.now) ⇒ Object
Get the rate per minute over the window.
-
#per_second(time: self.now) ⇒ Object
Get the rate per second over the window.
-
#total(time: self.now) ⇒ Object
Get the total count in the current window.
Constructor Details
#initialize(window: 60) ⇒ Rate
Initialize the event rate counter.
17 18 19 20 21 |
# File 'lib/async/container/statistics.rb', line 17 def initialize(window: 60) @window = window @samples = [0] * @window @last_update = Array.new(@window, 0) end |
Instance Attribute Details
#window ⇒ Object (readonly)
The time window in seconds for rate calculations.
24 25 26 |
# File 'lib/async/container/statistics.rb', line 24 def window @window end |
Instance Method Details
#add(value = 1, time: self.now) ⇒ Object
Add a value to the current time slot.
35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/async/container/statistics.rb', line 35 def add(value = 1, time: self.now) index = time % @samples.size # If this slot hasn't been updated in a full window cycle, reset it if (time - @last_update[index]) >= @window @samples[index] = 0 end @samples[index] += value @last_update[index] = time end |
#now ⇒ Object
Get the current time in seconds.
28 29 30 |
# File 'lib/async/container/statistics.rb', line 28 def now ::Process.clock_gettime(::Process::CLOCK_MONOTONIC).to_i end |
#per_minute(time: self.now) ⇒ Object
Get the rate per minute over the window.
71 72 73 |
# File 'lib/async/container/statistics.rb', line 71 def per_minute(time: self.now) per_second(time: time) * 60 end |
#per_second(time: self.now) ⇒ Object
Get the rate per second over the window.
64 65 66 |
# File 'lib/async/container/statistics.rb', line 64 def per_second(time: self.now) total(time: time).to_f / @window end |
#total(time: self.now) ⇒ Object
Get the total count in the current window.
50 51 52 53 54 55 56 57 58 59 |
# File 'lib/async/container/statistics.rb', line 50 def total(time: self.now) @samples.each_with_index.sum do |value, index| # Only count samples that are within the window (inclusive of window boundary) if (time - @last_update[index]) <= @window value else 0 end end end |