Given a log file with a series of values (message size, say), I need to calculate the average size over the last (some period) - this stuff is eventualy going to be shown as an mrtg graph.

I need to follow this stuff for various values, and for various periods of time, so I created the following code:

sub average_over_time { # # $ages[x,0] = time of article arrival # $ages[x,1] = age of article; # articles are thrown out of the pipe if they've arrived more than $ma +xage # ago. # my (@ages,$sumages); my $maxage=shift @_; return sub { my $limit=time-$maxage; # Squeeze out events that have timed out while (($#ages>-1) && ($ages[0][0]<$limit)) { $sumages-=$ages[0][1]; shift @ages; } if (defined($_[0])) { push(@ages,[time,$_[0]]); $sumages+=$_[0]; } $sumages=0 if $#ages == -1; return ($#ages>-1)?int($sumages/($#ages+1)):0; } } <code> That gives me the ability to say:<code> my $mail5=average_over_time(300); my $mail60=average_over_time(3600);
And later:
$db{"time-mail5"}=&$mail5($time); $db{"time-mail60"}=&$mail60($time);
I can also get out the average without putting in a value by calling it with $average=&$mail60(undef);.

Unfortunately, if you have a lot of events during the time period over which you're calculating, the array can get... a bit too large.

So I'm wondering, is there a method that I'm missing? Some way to calculate a running average over a given time period without having to keep all the values of that period in memory? And if at all possible without eating all of the CPU needed by the processes I'm monitoring?


In reply to Average over time by matija

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.