in reply to Re: Re: What is the fastest pure-Perl implementation of XXX?
in thread What is the fastest pure-Perl implementation of XXX?
yieldsuse Benchmark qw(:all); sub recurse { #divide and conquer unshift @_, 1 if 2 != @_; my ($m, $n) = @_; if ($m < $n) { my $k = int($m/2 + $n/2); return recurse($m, $k) * recurse($k+1, $n); } else { return $m } } sub iterate { my $result = 1; $result *= $_ for 2..shift; return $result } cmpthese(10_000, { 'recurse' => sub { recurse( 160) }, 'iterate' => sub { iterate( 160) }, });
If one uses Math::BigInt for larger factorials, then results even out a bit because of all the function calls needed to do multiplication. But if one can stick to the builtin operators and minimize function calls, it is usually a huge win in perl5.Benchmark: timing 10000 iterations of iterate, recurse... iterate: 2 wallclock secs ( 1.53 usr + 0.00 sys = 1.53 CPU) @ 65 +35.95/s (n=10000) recurse: 23 wallclock secs (22.82 usr + 0.00 sys = 22.82 CPU) @ 43 +8.21/s (n=10000) Rate recurse iterate recurse 438/s -- -93% iterate 6536/s 1392% --
-Mark
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: Re: What is the fastest pure-Perl implementation of XXX?
by tilly (Archbishop) on Mar 31, 2004 at 18:52 UTC | |
by kvale (Monsignor) on Mar 31, 2004 at 20:20 UTC |