Velocity Reviews > Ruby > Computing average of time deltas

# Computing average of time deltas

Peter Szinek
Guest
Posts: n/a

 03-19-2007
Hello,

Just to make sure I am not reinventing the wheel(tm) again: is there a
function/lib in Ruby which computes average of timespans? e.g.

--------
average 2s:000ms

TIA,
Peter
__
http://www.rubyrailways.com :: Ruby and Web2.0 blog
http://scrubyt.org :: Ruby web scraping framework
http://rubykitchensink.ca/ :: The indexed archive of all things Ruby

Phrogz
Guest
Posts: n/a

 03-19-2007
On Mar 19, 5:58 am, Peter Szinek <(E-Mail Removed)> wrote:
> Just to make sure I am not reinventing the wheel(tm) again: is there a
> function/lib in Ruby which computes average of timespans? e.g.
>
> --------
> average 2s:000ms

The Benchmark class lists an example of doing this for a fixed set of

require 'benchmark'

n = 50000
Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:",
">avg:") do |x|
tf = x.report("for:") { for i in 1..n; a = "1"; end }
tt = x.report("times:") { n.times do ; a = "1"; end }
tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
[tf+tt+tu, (tf+tt+tu)/3]
end

The result:

user system total real
for: 1.016667 0.016667 1.033333 ( 0.485749)
times: 1.450000 0.016667 1.466667 ( 0.681367)
upto: 1.533333 0.000000 1.533333 ( 0.722166)
>total: 4.000000 0.033333 4.033333 ( 1.889282)
>avg: 1.333333 0.011111 1.344444 ( 0.629761)

It would also be pretty easy to modify the Benchmark.bmbm method to do
this. Just sum and average the results calculated on line 277:
res = Benchmark::measure(&item)

A side note: if you have a never-ending sequence of 'tasks' (such as a
task repeated every update frame in a renderer) it is easier to
calculate - and sometimes more desirable - to use a low-pass filter
rather than a running average on a circular- or windowed-list.

For example:

The higher the 'inertia', the less the formula will react to
measurement spikes and the longer it will take to reach a new average.
The closer 'inertia' is to zero, the quicker it will react to changes.