Class: Twingly::Metrics::UniformSample

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

Instance Method Summary collapse

Constructor Details

#initialize(reservoir_size) ⇒ UniformSample

Returns a new instance of UniformSample.



9
10
11
12
# File 'lib/twingly/metrics/uniform_sample.rb', line 9

def initialize(reservoir_size)
  @values = Array.new(reservoir_size, 0)
  @count  = Atomic.new(0)
end

Instance Method Details

#clearObject



14
15
16
17
18
19
# File 'lib/twingly/metrics/uniform_sample.rb', line 14

def clear
  @values.length.times do |idx|
    @values[idx] = 0
  end
  @count.value = 0
end

#sizeObject



21
22
23
24
# File 'lib/twingly/metrics/uniform_sample.rb', line 21

def size
  count = @count.value
  [count, @values.length].min
end

#snapshotObject



26
27
28
# File 'lib/twingly/metrics/uniform_sample.rb', line 26

def snapshot
  Snapshot.new(@values.slice(0, size))
end

#update(value) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/twingly/metrics/uniform_sample.rb', line 30

def update(value)
  new_count = @count.update { |v| v + 1 }

  if new_count <= @values.length
    @values[new_count - 1] = value
  else
    idx = rand(new_count)
    @values[idx] = value if idx < @values.length
  end
end