Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference for how to calculate remainder?

Tags:

c++

performance

c

Lets suppose that a = 2^k is there any difference in terms of performance or correctness between int c = b%a and int c = b & (a-1)?

like image 898
Hossein Avatar asked May 14 '19 19:05

Hossein


1 Answers

For two’s complement int and a a power of two, b % a equals b & a-1 if and only if b is non-negative or a multiple of a.

As a consequence, a compiler can replace b % a by b & a-1 only if it knows b is non-negative or knows it is a multiple of a. (In the latter case, it should replace the expression with zero.) On typical current processors, an AND and a subtract instruction will be at least as fast, and often faster, than a remainder (divide) instruction, so b & a-1 is preferred, and the programmer seeking performance should use it if they know the conditions are satisfied, unless they are sure the compiler will generate an AND for b % a or they also want the quotient b/a. (If the quotient is desired, the compiler must generate a divide instruction, and processors typically provide the remainder along with the quotient.)

Of course, the compiler can be assured that b is non-negative by making it an unsigned int. Ensuring the compiler knows that a is a power of two is more complicated, unless a is a constant.

like image 176
Eric Postpischil Avatar answered Oct 20 '22 01:10

Eric Postpischil