Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Hello fair Monks. I am calculating the average of a given range of hash values. For example, given a hash like so:

%hash = ( 100 => '1', 101 => '23', 102 => '4', ... 200 => '75' );

I'd want to, say, calculate the average of the values at keys 100 to 125. I have a routine that does what I want, but it seems to be a bit slow. I can't think of any major optimizations (other than switching to an array, which isn't a good idea, since the hash keys are relatively large numbers). Perhaps someone has some ideas?

Here is my existing code:

#!/usr/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); my $data = {}; $data->{$_} = rand for (10000 .. 30000); print average($data, 15000, 25000), "\n"; cmpthese(50, { orig => sub { average($data, 15000, 25000) } }); sub average { my ($data, $start_point, $end_point) = @_; my @keys = sort keys %{ $data }; my $start_pos; my $end_pos; for (0 .. $#keys) { $start_pos = $_ if $keys[$_] eq $start_point; $end_pos = $_ if $keys[$_] eq $end_point; } return undef unless defined $start_pos and defined $end_pos; my $count = $end_pos - $start_pos + 1; my $amount; $amount += $data->{$keys[$_]} for ($start_pos .. $end_pos); return $amount / $count; }

Any help or ideas will be greatly appreciated. In case anybody wonders, I am using this routine to determine a moving average. I am running it many times against barely-differing ranges, so it slows down fairly quickly.


In reply to 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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-18 18:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found