Last active
June 28, 2023 10:55
-
-
Save nkokkos/10f30e93101412b70782c7d4b9c43e39 to your computer and use it in GitHub Desktop.
Revisions
-
nkokkos revised this gist
Jun 28, 2023 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,5 +1,5 @@ # RingBuffer class: # https://github.com/celluloid/celluloid/blob/master/lib/celluloid/logging/ring_buffer.rb # added the moving average method class RingBuffer -
nkokkos created this gist
Jun 28, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,78 @@ # RingBuffer class: # https://github.com/celluloid/celluloid/blob/5f41eb6f62f4a18ba40872c5b1b17ef0ce3eded6/lib/celluloid/logging/ring_buffer.rb # added the moving average method class RingBuffer attr_reader :buffer def initialize(size) @size = size @start = 0 @count = 0 @buffer = Array.new(size) @mutex = Mutex.new end def full? @count == @size end # calculates the mean average of all the values in the buffer provided that # the buffer is already full def average if self.full? @buffer.inject{ |sum, el| sum + el }.to_f / @size end end def empty? @count == 0 end def push(value) @mutex.synchronize do stop = (@start + @count) % @size @buffer[stop] = value if full? @start = (@start + 1) % @size else @count += 1 end value end end alias :<< :push def shift @mutex.synchronize do remove_element end end def flush values = [] @mutex.synchronize do while !empty? values << remove_element end end values end def clear @buffer = Array.new(@size) @start = 0 @count = 0 end private def remove_element return nil if empty? value, @buffer[@start] = @buffer[@start], nil @start = (@start + 1) % @size @count -= 1 value end end