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); } }, } );

In reply to Re: Explain Fibonacci one-liner ?? by Marshall
in thread Explain Fibonacci one-liner ?? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.