Thursday, January 6, 2022

Digest for comp.lang.c++@googlegroups.com - 2 updates in 1 topic

Bonita Montero <Bonita.Montero@gmail.com>: Jan 06 09:21AM +0100

I've written some code that resembles FileTimeToSystemTime from Win32.
In that code I did needed to get the month and the day from a FILETIME
(100ns-intervals) offset within a year. I did this with a binary search
on a table, but although the code isn't performance-critical I asked
myself if a linear search would be faster because there would be less
branch misspredictions than with the binary search - there are only a
few elements so that the linear search might be faster:
 
static
uint64_t const alignas(CL_SIZE) monthOffsets[2][12 + 1] =
{
{ 0 * DAY, 31 * DAY, 59 * DAY, 90 * DAY, 120 * DAY, 151 * DAY, 181 *
DAY, 212 * DAY, 243 * DAY, 273 * DAY, 304 * DAY, 334 * DAY, 999 * DAY },
{ 0 * DAY, 31 * DAY, 60 * DAY, 91 * DAY, 121 * DAY, 152 * DAY, 182 *
DAY, 213 * DAY, 244 * DAY, 274 * DAY, 305 * DAY, 335 * DAY, 999 * DAY }
};
uint64_t const *pMonthOffsets = monthOffsets[leapYear];
#if defined(BINARY_SEARCH)
size_t lower = 0, upper = 12, hit = -1, mid;
do
{
mid = (lower + upper) / 2;
if( pMonthOffsets[mid] <= tsCalc )
hit = mid,
lower = mid + 1;
else
upper = mid;
} while( lower != upper );
#else
size_t hit;
for( hit = 0; tsCalc >= pMonthOffsets[hit + 1]; ++hit );

No comments: