Skip to content

Instantly share code, notes, and snippets.

@julik
Created January 19, 2019 01:43
Show Gist options
  • Save julik/0abd93788293b1ab54cfa1b706570317 to your computer and use it in GitHub Desktop.
Save julik/0abd93788293b1ab54cfa1b706570317 to your computer and use it in GitHub Desktop.
class ThroughputCounter
WINDOW_SIZE = 256
Measurement = Struct.new(:n, :at)
def initialize(window_size: WINDOW_SIZE)
@wsize = window_size
@total_sent = 0
@measurements = [Measurement.new(0, now_monotonic)]
end
# Adds a new measurement
def <<(n)
@measurements << Measurement.new(n, now_monotonic)
@measurements.shift if @measurements.length > @wsize
@total_sent += n
self
end
def total
@total_sent
end
def avg_speed_per_second
delta_t = now_monotonic - @measurements.first.at
return 0 if delta_t < 0.001
delta_transfer = @measurements.map(&:n).inject(0.0, &:+)
delta_transfer / delta_t
end
def last_sample_at_monotonic
@measurements.last.at
end
def now_monotonic
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment