I sat through a discussion recently were discussing the 'expense' of the modulus operator. The individual who argued against it's used 'latency' as the prevailing theme.
I tend to agree with one party who claimed that such argument may have been true years ago. Modern compilers to day perform automatic strength reduction among other optimization techinques and they've gotten _really_ good at this. Long story short, profile and dont sweat the small stuff. As a test, I'd like to test alternatives to the use of modulo. I came up with the bitwise exclusive OR operator as one alternative and I'd like to know of others. See code below.
# include <iostream># include <vector># include <limits># include <ctime> int main() { int const USHORT_MAX = std::numeric_limits <unsigned short>::max() ; { bool mset_it = true ; for ( int odx = 0 ; odx < USHORT_MAX; ++odx ) { if ( mset_it ) { //std::cout << " nnnnn " << odx << std::endl; } mset_it ^= 1 ; } } { int count = 0 ; for ( int odx ( 0 ); odx < USHORT_MAX; ++odx ) { if ( count % 2 == 0 ) { //std::cout << " count " << count << std::endl; } ++count ; } }}
Note that the compiler might have already figured that out for himself, and might already have optimized your code like I showed.
itsmeandnobodyelse
>>>> I'd like to test alternatives to the use of modulo.
I didn't get it. How could a loop that runs from 0 to 65534 be an alternative to modulo function? Did I miss some past history?
Infinity08
Alex, the idea is to show only the even values in the range 0 to USHORT_MAX. The performance of two alternative implementations was compared. One implementation used the modulo operator, and another used a flag that was constantly inverted.