philiprehberger-rate_window
Time-windowed rate tracker with configurable resolution
Requirements
- Ruby >= 3.1
Installation
Add to your Gemfile:
gem "philiprehberger-rate_window"Or install directly:
gem install philiprehberger-rate_windowUsage
require "philiprehberger/rate_window"
tracker = Philiprehberger::RateWindow.new(window: 60, resolution: 1)
tracker.record(1)
tracker.record(5)
tracker.record(3)
tracker.rate # => events per second over the window
tracker.sum # => 9.0
tracker.count # => 3
tracker.average # => 3.0Percentiles
tracker = Philiprehberger::RateWindow.new(window: 60, resolution: 1)
100.times { |i| tracker.record(i) }
tracker.percentile(50) # => median value (with linear interpolation)
tracker.percentile(95) # => 95th percentile
tracker.percentile(99) # => 99th percentile
tracker.median # => shortcut for percentile(50)Min / Max
tracker = Philiprehberger::RateWindow.new(window: 60, resolution: 1)
tracker.record(5)
tracker.record(20)
tracker.record(3)
tracker.min # => 3.0
tracker.max # => 20.0Histogram
tracker = Philiprehberger::RateWindow.new(window: 60, resolution: 1)
100.times { |i| tracker.record(i) }
tracker.histogram(buckets: 5)
# => [
# { range: 0.0..20.0, count: ... },
# { range: 20.0..40.0, count: ... },
# ...
# ]Custom Resolution
# 5-minute window with 10-second buckets
tracker = Philiprehberger::RateWindow.new(window: 300, resolution: 10)
tracker.record(42)
tracker.rate # => rate per second over 5 minutesReset
tracker.reset
tracker.sum # => 0.0
tracker.count # => 0API
| Method | Description |
|---|---|
.new(window:, resolution:) |
Create a tracker with window (seconds) and bucket resolution |
#record(value = 1) |
Record a value in the current time bucket |
#rate |
Calculate rate per second over the window |
#sum |
Sum of all values in the window |
#count |
Number of recordings in the window |
#average |
Average value per recording |
#percentile(p) |
Calculate percentile (0-100) with linear interpolation |
#median |
Shortcut for percentile(50)
|
#min |
Minimum recorded value in the window |
#max |
Maximum recorded value in the window |
#histogram(buckets: 10) |
Value distribution as array of { range:, count: } hashes |
#reset |
Clear all recorded data |
Development
bundle install
bundle exec rspec
bundle exec rubocopSupport
If you find this project useful: