Home > front end >  C 20 Likely and UnLikely?
C 20 Likely and UnLikely?

Time:11-06

I was reading https://iq.opengenus.org/cpp-likely-and-unlikely-attributes/ and I don't understand/agree with few things.

  1. In the following code:

    void doModulus( vector<int> &vec , int mod ){
    
      // here the value of mod we are passing is 224, vec is of size 1024 holding values in [1,255]
    
      for( int i = 0 ; i<vec.size() ; i   )
      {
          if( vec[i] >= mod ) [[unlikely]]{
              // so we are prioritizing  else statement here
              vec[i] = vec[i] % mod ;
    
          }else {
    
              vec[i] = vec[i] ;                         
          }
      }
    }
    

does it matter or make any difference if we make the else code [[likely]] or this happens automatically in background as if one side is likely then the other side isn't? (Although I would like it to be that if the one side is unlikely then the other side (if it was likely) to be strongly likely.

  1. The following claim was made:

% operation is a computationally heavy operation for cpu , so let's try to optimize our code.

While the "optimize" refers to adding the if else conditions, but I tested the code using chrono and it seems execution time was 2-3 times faster without if-else...

Plus I don't see why % is heavy, it's just about reading bottom bits of number.

CodePudding user response:

does it matter or make any difference if we make the else code [[likely]] or this happens automatically in background as if one side is likely then the other side isn't?

The C Standard say about likely just recommended practice and example. See [dcl.attr.likelihood]. So it is up to the implementation how they are actually used.

Though recommended practice and example imply that only one mark is needed, and compilers where the difference is observed seem to imply this as well.

Plus I don't see why % is heavy, it's just about reading bottom bits of number.

Only for a power of two. But it should be known that is is power of two in compile time. There's also a way to make this operation cheaper for a known not a power of two constant (Why does GCC use multiplication by a strange number in implementing integer division?).

For a runtime value it is heavy, it is division.

It might happen that a value is known to the optimizer due to constant propagation though. Then optimizations apply.

  • Related