[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Factorial Elegance



abigail, thanks for taking a look at my flawed benchmark. Out of
curiosity I changed it to give each method it's real effect, i.e. with
caching where implemented. My conclusion is that array lookups are way
faster than tied hash lookups.

Hope you have a very nice day, :-)
Tim Ayers (tayers@bridge.com)

__DATA__
#!/opt/perl/bin/perl -w

use strict;
use Benchmark;

use Tie::Math qw(f X);
use vars qw /%factorial/;
tie %factorial, 'Tie::Math', sub { f(X) = X * f(X-1) },
                             sub { f(0) = 0;  f(1) = 1; };
sub schwern {
  local $^W;
  my $x = shift;
  return $factorial{$x};
}

sub klement {
  return eval join '*', 1 .. shift;
}

{
my @cache = (1);
sub tayers {
  my $x = shift;
  return undef if $x < 0;
  unless (defined $cache[$x]) {
    my $p = $cache[$#cache];
    $cache[$_] = $p *= $_ for ($#cache+1..$x);
  }
  return $cache[$x];
}
}

sub abigail {
  my ($r  => $x) = (1, shift);
  do {$r *=  $x} while $x -- > 2;
  $r;
}

timethese(-5, 
  {
   schwern => 'schwern(170);',
   klement => 'klement(170);',
   tayers  => 'tayers(170);',
   abigail => 'abigail(170);'
  });

__END__
Benchmark: running abigail, klement, schwern, tayers, each for at least 5 CPU seconds...
   abigail:  5 wallclock secs ( 5.22 usr +  0.00 sys =  5.22 CPU) @ 5460.15/s (n=28502)
   klement:  5 wallclock secs ( 5.33 usr +  0.00 sys =  5.33 CPU) @ 388.37/s (n=2070)
   schwern:  5 wallclock secs ( 5.30 usr +  0.00 sys =  5.30 CPU) @ 17068.11/s (n=90461)
    tayers:  6 wallclock secs ( 5.31 usr +  0.00 sys =  5.31 CPU) @ 154624.86/s (n=821058)


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe