If your lucky enough to have access to the XS version of List::Util this would probably run much faster still.

sub buk { use List::Util qw[sum]; my( $hashref, $start, $end ) = @_; # Added sanity check. Slowed it a tad return undef unless exists $hashref->{$start} and exists $hashref->{$end}; my @keys = grep{ $_ >= $start && $_ <= $end } keys %{ $hashref }; return sum( @{ $hashref }{ @keys } ) / @keys; } __END__ P:\test>278169 0.503353665487943 0.503353665487943 Rate orig buk orig 1.28/s -- -42% buk 2.23/s 73% --

Second attempt (417%)

Once I noticed that your code assumes that a contiguous range of keys will exist between the start and end values, it can go much quicker.

sub buk2 { use List::Util qw[sum]; return undef unless exists $_[0]->{ $_[1] } and exists $_[0]->{ $_[2] }; return sum( @{ $_[0] }{ $_[1] .. $_[2] } ) / ( $_[2] - $_[1] + 1 ) +; } __END__ P:\test>278169 0.503353665487943 0.503353665487943 0.503353665487943 Rate orig buk buk2 orig 1.30/s -- -41% -81% buk 2.19/s 69% -- -67% buk2 6.70/s 417% 206% --

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller


In reply to Re: calculate average from range of hash values (73%) by BrowserUk
in thread calculate average from range of hash values (optimize) by revdiablo

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.