For speed, I'd suggest:
sub test6 {
my $n = $_[0] & $_[1];
my $count = 0;
++$count, $n &= $n - 1 while $n;
$count;
}
For beauty I'd suggest hiding that behind a suitable function name - it costs an extra function call, but you can probably lose that in the way you call it when not benchmarking:
sub countbits {
my($n, $count) = ($_[0], 0);
++$count, $n &= $n - 1 while $n;
return $count;
}
sub test7 {
my($iDays, $iCmp) = @_;
return countbits($iDays & $iCmp);
}
You might even want to add some comments. :)
Benchmarks:
Rate Test4 Test5 Test7 Test6
Test4 106192/s -- -38% -40% -57%
Test5 172463/s 62% -- -3% -31%
Test7 176987/s 67% 3% -- -29%
Test6 248686/s 134% 44% 41% --
Hugo
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.