Class: R4r::WindowedAdder

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

Overview

A Ruby port of the finagle’s WindowedAdder.

Instance Method Summary collapse

Constructor Details

#initialize(range_ms:, slices:, clock: nil) ⇒ WindowedAdder

Creates a time-windowed version of a {Concurrent::ThreadSafe::Util::Adder].

Parameters:

  • range_ms (Fixnum)

    the range of time in millisecods to be kept in the adder.

  • slices (Fixnum)

    the number of slices that are maintained; a higher number of slices means finer granularity but also more memory consumption. Must be more than 1.

  • clock (R4r::Clock) (defaults to: nil)

    the current time. for testing.

Raises:

  • (ArgumentError)

    if slices is less then 1

  • (ArgumentError)

    if range is nil

  • (ArgumentError)

    if slices is nil



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

#incrObject

Increment the adder by 1



47
48
49
# File 'lib/r4r/windowed_adder.rb', line 47

def incr
  add(1)
end

#resetObject

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

#sumFixnum

Retrieve the current sum of the adder

Returns:

  • (Fixnum)


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