Robin Sheat wrote:
> I have a section of a program that is this:
> 
>         my $users = get_all_users();
>         foreach my $user (@$users) {
>                 my $details = get_user_details($user);
>                 my $sum=0;
>                 my $count=0;
>                 for (my $i=1; $i<@$details; $i+=2) {
>                         $sum += @$details[$i];
>                         $count++;
>                 }
>                 $means{$user} = $sum/$count;
>         }
> 
> The $users var is a reference to an array that is about 450,000 entries. The 
> $details var is an array reference typically of size around 500 or so (note 
> however, the inner loop goes up in twos). Overall the innermost part is 
> executed 100 million times. How can I optimise it?

Write it in C.   :-)


> If I was using C, I'd use 
> pointer arithmetic on the array to save the multiplication on the array 
> indexing. A naive reading of this implies that Perl would be doing a multiply 
> for every array access, is this the case, or is it optimised away? If not, is 
> there a way to use pointer arithmetic (or something that behaves similarly, 
> but probably safer)?

Yes, Perl uses references which are conceptually similar to pointers.

        my $users = get_all_users();
        for ( my $i = 0; $i < @$users; ++$i ) {
                my $details = get_user_details( $users->[ $i ] );
                my $sum   = 0;
                my $count = 0;
                for ( my $j = 1; $j < @$details; $j += 2 ) {
                        $sum += $details->[ $j ];
                        $count++;
                }
                $means{ $user } = $sum / $count;
        }

Although in my tests that takes about the same time to execute but uses a
*lot* less memory as it doesn't have to make a copy of the @$users array like
your version does.


> It is probably possible to restructure the array so that 
> it can go up in ones, and do a foreach, but in most cases it'll be common to 
> want both values, which is why I didn't do that.
> 
> Anyone know any good resources for this kind of thing?

perldoc -q "How do I profile my Perl programs"

http://www.ccl4.org/~nick/P/Fast_Enough/



John
-- 
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order.       -- Larry Wall

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to