Class: Twingly::Metrics::SimpleMovingAverage

Inherits:
Object
  • Object
show all
Defined in:
lib/twingly/metrics/simple_moving_average.rb

Constant Summary collapse

INTERVAL =
5.0
SECONDS_PER_MINUTE =
60.0
ONE_MINUTE =
1
FIVE_MINUTES =
5
FIFTEEN_MINUTES =
15

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(duration, interval) ⇒ SimpleMovingAverage

Returns a new instance of SimpleMovingAverage.



27
28
29
30
31
32
33
# File 'lib/twingly/metrics/simple_moving_average.rb', line 27

def initialize(duration, interval)
  @interval = interval
  @duration = duration

  @values = Array.new((duration / interval).to_i) { Atomic.new(nil) }
  @index  = Atomic.new(0)
end

Class Method Details

.new_m1Object



15
16
17
# File 'lib/twingly/metrics/simple_moving_average.rb', line 15

def self.new_m1
  new(ONE_MINUTE * SECONDS_PER_MINUTE, INTERVAL)
end

.new_m15Object



23
24
25
# File 'lib/twingly/metrics/simple_moving_average.rb', line 23

def self.new_m15
  new(FIFTEEN_MINUTES * SECONDS_PER_MINUTE, INTERVAL)
end

.new_m5Object



19
20
21
# File 'lib/twingly/metrics/simple_moving_average.rb', line 19

def self.new_m5
  new(FIVE_MINUTES * SECONDS_PER_MINUTE, INTERVAL)
end

Instance Method Details

#clearObject



35
36
37
38
39
40
# File 'lib/twingly/metrics/simple_moving_average.rb', line 35

def clear
  @values.each do |value|
    value.value = nil
  end
  @index.value = 0
end

#rateObject



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/twingly/metrics/simple_moving_average.rb', line 51

def rate
  num = 0.0
  count = 0.0

  @values.each do |value|
    if (v = value.value)
      num   += v
      count += 1
    end
  end

  return 0.0 if count.zero?

  num / count / @interval.to_f
end

#tickObject



46
47
48
49
# File 'lib/twingly/metrics/simple_moving_average.rb', line 46

def tick
  next_index = @index.update { |v| v < @values.length - 1 ? v + 1 : 0 }
  @values[next_index].value = nil
end

#update(value) ⇒ Object



42
43
44
# File 'lib/twingly/metrics/simple_moving_average.rb', line 42

def update(value)
  @values[@index.value].update { |v| v ? v + value : value }
end