Hi all,
I have a very simple bit of code where I basically want to set a var $wait value to 0 if it is a negative number and stay as is if not. This resulted in a debate with a work colleague as to which of the following lines would be faster.
so we tested . . .
use Benchmark qw( cmpthese ) ;
my $wait = -34;
cmpthese( -2, {
a=>sub{
$wait = $wait < 0 ? 0 : $wait ;
$wait = -34;
},
b=>sub{
if ($wait < 0 ){ $wait = 0};
$wait = -34;
},
c=>sub{
$wait = 0 unless $wait > 0;
$wait = -34;
},
d=>sub{
$wait = 0 unless abs($wait);
$wait = -34;
},
and we were amazed by the results . . ..
with a negative number:
Rate a b c d
a 4216652/s -- -16% -17% -36%
b 5010637/s 19% -- -2% -24%
c 5094673/s 21% 2% -- -23%
d 6616606/s 57% 32% 30% --
with a positive number:
Rate a b c d
a 3542992/s -- -5% -6% -50%
b 3742730/s 6% -- -1% -47%
c 3766874/s 6% 1% -- -47%
d 7084993/s 100% 89% 88% --
Two questions -
- why would using abs be so much faster - (intuitively I felt using a function would add to the cost)?
- has anyone got a faster way?
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.