Class: Metrics::Statistics::ExponentialSample

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-metrics/statistics/exponential_sample.rb

Constant Summary collapse

RESCALE_WINDOW_SECONDS =

1 hour

60 * 60

Instance Method Summary collapse

Constructor Details

#initialize(size = 1028, alpha = 0.015) ⇒ ExponentialSample

Returns a new instance of ExponentialSample.



6
7
8
9
10
# File 'lib/ruby-metrics/statistics/exponential_sample.rb', line 6

def initialize(size = 1028, alpha = 0.015)
  @size   = size
  @alpha  = alpha
  clear
end

Instance Method Details

#clearObject



12
13
14
15
16
17
# File 'lib/ruby-metrics/statistics/exponential_sample.rb', line 12

def clear
  @values           = { }
  @start_time       = tick
  @next_scale_time  = Time.now.to_f + RESCALE_WINDOW_SECONDS
  @count            = 0
end

#sizeObject



19
20
21
# File 'lib/ruby-metrics/statistics/exponential_sample.rb', line 19

def size
  [@values.size, @count].min
end

#tickObject



23
24
25
# File 'lib/ruby-metrics/statistics/exponential_sample.rb', line 23

def tick
  Time.now.to_f
end

#update(value) ⇒ Object



27
28
29
# File 'lib/ruby-metrics/statistics/exponential_sample.rb', line 27

def update(value)
  update_with_timestamp(value, tick)
end

#update_with_timestamp(value, timestamp) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ruby-metrics/statistics/exponential_sample.rb', line 31

def update_with_timestamp(value, timestamp)
  priority = weight(timestamp.to_f - @start_time.to_f) / rand
  @count += 1
  if @count <= @size
    @values[priority] = value
  else
    first_key = @values.keys.first
    if first_key && first_key < priority
      @values[priority] = value
      
      while values.any? && @values.delete(first_key).nil?
        first_key = @values.keys.first
      end
    end
  end
  
  now = Time.now.to_f

  if now >= @next_scale_time
    rescale(now + RESCALE_WINDOW_SECONDS)
  end
end

#valuesObject



54
55
56
57
58
59
# File 'lib/ruby-metrics/statistics/exponential_sample.rb', line 54

def values
  # read-lock?
  @values.keys.sort.map do |key|
    @values[key]
  end
end