Class: QuartzTorrent::Rate
- Inherits:
-
Object
- Object
- QuartzTorrent::Rate
- Defined in:
- lib/quartz_torrent/rate.rb
Overview
Class that keeps track of a rate, for example a download or upload rate. The class is used by calling ‘update’ with samples (numbers) representing the amount of units being measured accrued since the last call, and value returns the rate in units/second.
This is implemented as an exponential moving average. The weight of the current sample is based on an exponention function of the time since the last sample. To reduce CPU usage, when update is called with a new sample the new average is not calculated immediately, but instead the samples are summed until 1 second has elapsed before recalculating the average.
Instance Method Summary collapse
-
#initialize(avgPeriod = 4.0) ⇒ Rate
constructor
Create a new Rate that measures the rate using samples.
-
#reset ⇒ Object
Reset the rate to empty.
-
#update(sample) ⇒ Object
Update the rate by passing another sample (number) representing units accrued since the last call to update.
-
#value ⇒ Object
Get the current rate.
Constructor Details
#initialize(avgPeriod = 4.0) ⇒ Rate
Create a new Rate that measures the rate using samples. avgPeriod specifies the duration over which the samples are averaged.
15 16 17 18 |
# File 'lib/quartz_torrent/rate.rb', line 15 def initialize(avgPeriod = 4.0) reset @avgPeriod = avgPeriod.to_f end |
Instance Method Details
#reset ⇒ Object
Reset the rate to empty.
40 41 42 43 44 |
# File 'lib/quartz_torrent/rate.rb', line 40 def reset @value = nil @time = Time.new @sum = 0.0 end |
#update(sample) ⇒ Object
Update the rate by passing another sample (number) representing units accrued since the last call to update.
28 29 30 31 32 33 34 35 36 37 |
# File 'lib/quartz_torrent/rate.rb', line 28 def update(sample) now = Time.new elapsed = now - @time @sum += sample if elapsed > 1.0 @value = newValue elapsed, @sum/elapsed @time = now @sum = 0.0 end end |
#value ⇒ Object
Get the current rate. If there are too few samples, 0 is returned.
21 22 23 24 |
# File 'lib/quartz_torrent/rate.rb', line 21 def value update 0 @value ? @value : 0.0 end |