On Fri, Apr 17, 2009 at 12:16, Jim Gibson <jimsgib...@gmail.com> wrote:
> On 4/16/09 Thu  Apr 16, 2009  1:39 PM, "edw...@yandex.ru" <edw...@yandex.ru>
> scribbled:
>
>> Hello,
>>
>> I would like to know, how to force perl unfold "foreach" expression during 
>> the
>> compilation, i.e. I want next code:
snip
> Can you explain why you want to do this?
snip

It is called loop unrolling and is a performance hack that many
compilers perform when passed a switch to optimize the code it
generates.

Perl does do some optimization (such as constant folding), but I do
not believe you have any control over it and I am nearly 100% certain
it does not unroll loops for you.  If you have need of that sort of
micro-optimization you probably shouldn't be using Perl, or you should
be looking into using XS or Inline::C for the high cost loops.

snip
> I suggest you write a program that measures the execution times for the
> iterative-loop case and the unfolded case and compare them to see if you
> will gain enough execution time (if that is indeed what you are seeking) to
> justify the additional memory needed to contain the unwrapped block
> statements. (Were I to do this, I would write a Perl program to generate the
> Perl program!) See the Benchmark module.
snip

Manually unrolling the loop gives you a modest increase in speed for
1,000 items:

forloop: 500500
unrolled: 500500
           Rate  forloop unrolled
forloop  4034/s       --     -31%
unrolled 5852/s      45%       --


But almost no benefit for 100,000 items:

forloop: 5000050000
unrolled: 5000050000
           Rate  forloop unrolled
forloop  38.6/s       --      -1%
unrolled 38.9/s       1%       --



#!/usr/bin/perl

use strict;
use warnings;

use List::Util qw/sum/;
use Benchmark;

my $unrolled = 'sub unrolled { my @a; ';
for my $i (0 .. 1_000) {
        $unrolled .= "\$a[$i] = $i;";
}
$unrolled .= 'return \...@a; }; 1';

eval $unrolled or die $@;

my %subs = (
        forloop => sub {
                my @a;
                for my $i (0 .. 1_000) {
                        $a[$i] = $i;
                }
                return \...@a;
        },
        unrolled => \&unrolled
);

for my $sub (sort keys %subs) {
        print "$sub: ", sum(@{$subs{$sub}->()}), "\n";
}

Benchmark::cmpthese(-2, \%subs);



-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to