Class: R4r::WindowedAdder
- Inherits:
-
Object
- Object
- R4r::WindowedAdder
- Defined in:
- lib/r4r/windowed_adder.rb
Overview
A Ruby port of the finagle’s WindowedAdder.
Instance Method Summary collapse
-
#add(x) ⇒ Object
Increment the adder by ‘x`.
-
#incr ⇒ Object
Increment the adder by 1.
-
#initialize(range_ms:, slices:, clock: nil) ⇒ WindowedAdder
constructor
Creates a time-windowed version of a {Concurrent::ThreadSafe::Util::Adder].
-
#reset ⇒ Object
Reset the state of the adder.
-
#sum ⇒ Fixnum
Retrieve the current sum of the adder.
Constructor Details
#initialize(range_ms:, slices:, clock: nil) ⇒ WindowedAdder
Creates a time-windowed version of a {Concurrent::ThreadSafe::Util::Adder].
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/r4r/windowed_adder.rb', line 23 def initialize(range_ms:, slices:, clock: nil) raise ArgumentError, "range_ms cannot be nil" if range_ms.nil? raise ArgumentError, "slices cannot be nil" if slices.nil? raise ArgumentError, "slices must be positive" if slices.to_i <= 1 @window = range_ms.to_i / slices.to_i @slices = slices.to_i - 1 @writer = 0 #::Concurrent::ThreadSafe::Util::Adder.new @gen = 0 @expired_gen = 0 #::Concurrent::AtomicFixnum.new(@gen) @buf = Array.new(@slices) { 0 } @index = 0 @now = (clock || R4r.clock) @old = @now.call end |
Instance Method Details
#add(x) ⇒ Object
Increment the adder by ‘x`
52 53 54 55 56 |
# File 'lib/r4r/windowed_adder.rb', line 52 def add(x) expired if (@now.call - @old) >= @window @writer += x end |
#incr ⇒ Object
Increment the adder by 1
47 48 49 |
# File 'lib/r4r/windowed_adder.rb', line 47 def incr add(1) end |
#reset ⇒ Object
Reset the state of the adder.
40 41 42 43 44 |
# File 'lib/r4r/windowed_adder.rb', line 40 def reset @buf.fill(0, @slices) { 0 } @writer = 0 @old = @now.call end |
#sum ⇒ Fixnum
Retrieve the current sum of the adder
61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/r4r/windowed_adder.rb', line 61 def sum expired if (@now.call - @old) >= @window value = @writer i = 0 while i < @slices value += @buf[i] i += 1 end value end |