in reply to Re: Multiplying together the numers in an array
in thread Multiplying together the numers in an array
This is a bit odd. I ran the sames tests because i wanted to see how a map solution measured up.
#!/usr/bin/perl use Benchmark qw(cmpthese); use List::Util qw(reduce); cmpthese (-5, { 'initial' => sub { my @numbers = (2,3,4,5); my $total = 1; for(@numbers){ $total = ($total * $_); } }, 'listutil' => sub { my @numbers = (2,3,4,5); reduce{ $a*=$b } @numbers; }, 'eval' => sub { my @numbers = (2,3,4,5); eval join "*", @numbers; }, '*=' => sub { my @numbers = (2,3,4,5); my $total=1; $total *= $_ for @numbers; }, 'map' => sub { my @numbers = (2,3,4,5); my $total=1; map { $total *= $_ } @numbers; }, 'reducing' => sub { my @numbers = (2,3,4,5); $numbers[0] *= pop @numbers while ( @numbers > 1 ); }, });
And got the followin results on two runs.
C:\test>perl reduce.pl Rate eval listutil initial *= map reducin +g eval 19089/s -- -86% -90% -91% -93% -93 +% listutil 136513/s 615% -- -27% -39% -47% -51 +% initial 187039/s 880% 37% -- -16% -27% -33 +% *= 223842/s 1073% 64% 20% -- -13% -20 +% map 256001/s 1241% 88% 37% 14% -- -8 +% reducing 278189/s 1357% 104% 49% 24% 9% - +- C:\test>perl reduce.pl Rate eval listutil initial *= reducing ma +p eval 19656/s -- -87% -92% -92% -93% -94 +% listutil 150598/s 666% -- -35% -39% -47% -51 +% initial 232290/s 1082% 54% -- -6% -19% -24 +% *= 247322/s 1158% 64% 6% -- -14% -20 +% reducing 286024/s 1355% 90% 23% 16% -- -7 +% map 307455/s 1464% 104% 32% 24% 7% - +- C:\test>
It greatly surpised me how much slower the listutil function was on my machine. Are there different implementations of it for different platforms that would cause this? Or is the small number of array elements makeing everything else meaningless?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: Multiplying together the numers in an array
by ihb (Deacon) on Apr 09, 2004 at 21:17 UTC |