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

Re: [FWP] Factorial Elegance



>>>>> "a" == abigail  <abigail@foad.org> writes:
a> You posted a question about the results of a benchmark, without including
a> the benchmark itself. Since benchmarking is non-trivial, and leaves lots
a> of rooms for errors, such questions without knowing the circumstances are
a> impossible to answer. You might as well ask for the results of next weeks
a> lottery.

D'accord. I used the following.

  #!/usr/bin/perl -w
  
  use strict;
  use Benchmark;
  
  use Tie::Math qw(f X);
  my %factorial = ();
  tie %factorial, 'Tie::Math', sub { f(X) = X * f(X-1) },
                               sub { f(0) = 0;  f(1) = 1; };
  sub schwern {
    my $x = shift;
    return $factorial{$x};
  }
  
  sub klement {
    return eval join '*', 1 .. shift;
  }
  
  my @cache = (1);
  sub tayers {
    my $x = shift;
    @cache = (1);
    return undef if $x < 0;
    unless (defined $cache[$x]) {
      my $p = $cache[$#cache];
      $cache[$_] = $p *= $_ for ($#cache+1..$x);
    }
    return $cache[$x];
  }
  
  timethese(7000,
   {schwern => '%factorial=();schwern(170);',
    klement => 'klement(170);',
    tayers  => '@cache=(1);tayers(170);'
   });

I'm probably misunderstanding the TIE-mechanism. Thanks for the help and 
Hope you have a very nice day, :-)
Tim Ayers (tayers@bridge.com)


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