in reply to Factorial algorithm execution time

I think creation of the BigInt objects might be mucking stuff up. Simplify the test. Loop is faster, and it gets faster as the argument gets bigger.

YuckFoo


Benchmark: timing 16000 iterations of nocurse, recurse...
   nocurse:  0 wallclock secs 
      ( 0.20 usr +  0.00 sys =  0.20 CPU) @ 80000.00/s (n=16000)
   recurse:  1 wallclock secs 
      ( 0.51 usr +  0.00 sys =  0.51 CPU) @ 31372.55/s (n=16000)
#!/usr/bin/perl use Benchmark; $fact = $ARGV[0] || 10; timethese(16000, {'recurse'=>'recurse($fact)', 'nocurse'=>'nocurse($fact)'}); sub recurse { my ($n) = @_; if ($n == 0) { return 1; } return ($n * recurse($n-1)); } sub nocurse { my ($n) = @_; my $f = 1; for my $i (1..$n) { $f *= $i; } return $f; }

Replies are listed 'Best First'.
Re: Re: Factorial algorithm execution time
by gri6507 (Deacon) on Oct 17, 2002 at 20:33 UTC
    The reason BigInt was there was to allow for calculations of 1000! or larger (which was the original intent). However, I don't see how this alone could explain the timing differences. For example, in my original code, the recursive function
    • Created one new BigInt
    • Compared two BigInts
    • Multiplied two BigInts
    • Subtracted 2 BigInts

    The non-recursive function
    • Created 2 BigInts
    • Multiplied 2 BigInts

    In other words, are you saying that memory allocation for one extra BigInt is that slow??