Skip to content
This repository has been archived by the owner on May 11, 2023. It is now read-only.

Commit

Permalink
Add TimeWindow
Browse files Browse the repository at this point in the history
  • Loading branch information
zhulik committed Feb 10, 2023
1 parent 160a2ea commit 5ea0b68
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions lib/nats_streamer/metrics/time_window.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# frozen_string_literal: true

class NatsStreamer::Metrics::TimeWindow
include NatsStreamer::Helpers

option :duration, type: T::Integer # milliseconds

def push(value)
purge_old!
history << [timestamp, value]
end

def stats
purge_old!
values = history.map { _1[1] }

avg = values.count.positive? ? values.sum.to_f / values.count : nil

min, max = values.minmax
{
min:,
max:,
avg:,
count:
}
end

def count = history.count

private

memoize def history = []

def timestamp = (Time.now.to_f * 1000).to_i

def purge_old!
now = timestamp

index = history.bsearch_index { _1.first > (now - duration) }
history.clear if index.nil?
history.shift(index) if index
end
end

0 comments on commit 5ea0b68

Please sign in to comment.