- First off, i43s's code fails to compile for me using perl 5.6.0
with -w, with the following:
Warning: Use of "shift" without parens is ambiguous
at benchadd.pl line 3.
Type of arg 1 to shift must be array (not shift)
at benchadd.pl line 3, near "shift,"
This is fixed by adding explicit parenthesis after every shift().
- Second, mdillon's code as is returns undef, because
the "my $sum" is part of the loop (I think that's the reason,
at least). Separating the declaration of the variable from
the suming loop fixes the problem.
- Third, I have benchmarked
th three solutions proposed so far (i43s, davorg and mdillon)
using the code below. The results show:
Benchmark: timing 100000 iterations of davorg, i43s, mdillon...
davorg: 70 wallclock secs (55.52 usr + 0.06 sys =
55.58 CPU) @ 1799.21/s (n=100000)
i43s: 20 wallclock secs (15.47 usr + 0.00 sys =
15.47 CPU) @ 6464.12/s (n=100000)
mdillon: 8 wallclock secs ( 6.77 usr + 0.00 sys =
6.77 CPU) @ 14771.05/s (n=100000)
So my comments are:
- davorg: nice trick with eval, but eval is just too slow.
- i43s: nice recursive subroutine, but recursion is also
expensive, and IMHO it complicates the code in this case.
- mdillon: that's how I would have done it too :-)
--ZZamboni
The benchmarking code:
use Benchmark;
sub add_i43s { @_ > 1 ? add_i43s( shift() + shift(), @_ ) : shift() }
sub add_davorg { eval join '+', @_ };
sub add_mdillon { my $sum; $sum += $_ for @_; $sum }
timethese(100000, {
'i43s' => sub { add_i43s(1,2,3,4,5,6,7,8,9,10); },
'davorg' => sub { add_davorg(1,2,3,4,5,6,7,8,9,10); },
'mdillon' => sub { add_mdillon(1,2,3,4,5,6,7,8,9,10); } });
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.