Link to home
Create AccountLog in
Avatar of forums_mp
forums_mp

asked on

modulus operator

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 ;
        }
     }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Note that the compiler might have already figured that out for himself, and might already have optimized your code like I showed.
>>>> 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?
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.

At least that's how I understood it.
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account