in reply to Explain Fibonacci one-liner ??

I ran some benchmarks on this fibonacci code.
The JavaFan code is the fastest. My code is 2nd. There is no 3rd, 4th or 5th place. Things go "downhill" very fast (not just factor of 2x, 3x, but orders of magnitude).
#!/usr/bin/perl -w use feature qw(say); use Memoize; use Benchmark; =results: Benchmark: timing 100000 iterations of JavaFan, Marshall, Memoize, Recurse... JavaFan: 2 wallclock secs ( 2.00 usr + 0.00 sys = 2.00 CPU) @ 49975.01/s (n=100000) Marshall: 6 wallclock secs ( 6.59 usr + 0.00 sys = 6.59 CPU) @ 15165.30/s (n=100000) Memoize: 50 wallclock secs (49.45 usr + 0.25 sys = 49.70 CPU) @ 2011.99/s (n=100000) Recurse: 644 wallclock secs (641.27 usr + 0.05 sys = 641.31 CPU) @ 155.93/s (n=100000) =cut timethese (100000, { JavaFan=> q{ sub fib { my $PHI = (1 + sqrt(5)) / 2; int($PHI ** $_[0] / sqrt(5) + 0.5) } foreach (0 .. 15) { # print fib($_), "\n"; fib($_); } }, Marshall => q{ foreach (1..15) { # print fibonacci($_), " "; fibonacci($_); } sub fibonacci { my $number = shift; my $cur_num = 1; my $prev_num = 1; my $sum; return 1 if ($number == 1 || $number == 2); $number -= 2; while ($number--) { $sum = $cur_num + $prev_num; $prev_num = $cur_num; $cur_num = $sum; } return $sum; } }, Recurse => q{ foreach (1..15) { # print fibx($_), "\n"; fibx($_); } # Compute Fibonacci numbers sub fibx { my $n = shift; return $n if $n < 2; fibx($n-1) + fibx($n-2); } }, Memoize => q{ memoize('fiby'); foreach (1..15) { fiby($_); #print fiby($_); } # Compute Fibonacci numbers sub fiby { my $n = shift; return $n if $n < 2; fiby($n-1) + fiby($n-2); } }, } );

Replies are listed 'Best First'.
Re^2: Explain Fibonacci one-liner ??
by JavaFan (Canon) on May 10, 2010 at 22:22 UTC
    The JavaFan code is the fastest. My code is 2nd. There is no 3rd, 4th or 5th place. Things go "downhill" very fast (not just factor of 2x, 3x, but orders of magnitude).
    Actually, so does yours. It's just not visible because of the very limited range. Upping the range to 1..90 gives:
    Benchmark: running JavaFan, Marshall for at least 2 CPU seconds... JavaFan: 2 wallclock secs ( 2.18 usr + 0.00 sys = 2.18 CPU) @ 44 +81.19/s (n=9769) Marshall: 1 wallclock secs ( 2.00 usr + 0.00 sys = 2.00 CPU) @ 34 +2.50/s (n=685)
    Also note that your move to put the assignment of $PHI inside the subroutine reduced the running speed by about 10% (it does 5063.11 iterations/s with $PHI only assigned to once).

    Incrementing the range even further would increase the difference even more, but for some N between 90 and 100, F(N) no longer fits inside a 64bit integer. And I didn't want to spend the time to write a benchmark using Math::BigFloat/Math::BigInt.

      I don't want to write more benchmarks either. I think enough said about this. If the Op wants to beat it to death..he/she has a lot of info to work with.