Dear Monks,
I have currently a set of values for weekdays, that is stored as integer. To clarify here are example binary values:
Mon = 0b0000001 = 1
Tue = 0b0000010 = 2
Mon to Fri = 0b0011111 = 31
Sat to Sun = 0b1100000 = 96
I need to know how many days of running two sets of data have in common. This is a simple task, however I got stuck in a vicious circle between simplicity and performance. I st up five test functions and compared their speed. It did not surprise me much, that the fastes way is a bitwise evaluation. But if I ran through all days with a loop, the function is a lot slower. Can anyone suggest a better way to approach this? Please find the current code below.
sub test4 {
my ( $iDays, $iCmp ) = @_;
my $iRes = 0;
for ( 1, 2, 4, 8, 16, 32, 64 ){
if ( $iDays & $iCmp & $_ ){
$iRes++;
}
}
return $iRes;
}
sub test5 {
my ( $iDays, $iCmp ) = @_;
my $iRes = 0;
$iRes++ if ( $iDays & $iCmp & 1 );
$iRes++ if ( $iDays & $iCmp & 2 );
$iRes++ if ( $iDays & $iCmp & 4 );
$iRes++ if ( $iDays & $iCmp & 8 );
$iRes++ if ( $iDays & $iCmp & 16 );
$iRes++ if ( $iDays & $iCmp & 32 );
$iRes++ if ( $iDays & $iCmp & 64 );
return $iRes;
}
cmpthese($count, {
'Test4' => sub { test4( int ( rand(127) ), int( rand(127) ) ) },
'Test5' => sub { test5( int ( rand(127) ), int( rand(127) ) ) }
});
__DATA__
Rate Test4 Test5
Test4 162690/s -- -46%
Test5 300000/s 84% --
The performance lost by the loop is quite steep, but the code nicer.
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.