Re:Efficient C Tip – use the modulus (%) operator with caution
by tspiteri on Tuesday February 08, 2011 @07:02PM
(#2195512)
... if the expression can't be reduced to multiplications/shifts/addition due to division by a constant.
Ah, I missed that. Even on normal processors, for the following:
int div60(int i) { return i / 60; }
int mod60(int i) { return i % 60; }
gcc uses one multiplication and some shifts/additions for div60() and two multiplications and some shifts/additions for mod60().
Re:Efficient C Tip – use the modulus (%) operator with caution
by caf on Tuesday February 08, 2011 @08:38PM
(#2195832)
In any case, once you've done the division, the remainder is practically free; the article is basically an illustration of how bad the compilers in question are at spotting this fact.
This is probably the rationale behind the standard div() function, that calculates division and modulus together - it should make it easier for less sophisticated compilers to take advantage of this.
Where you're not using the division instruction, modulo can actually be faster than division itself. The extreme case are powers of 2 of course; on x86, a right shift is vastly more expensive than a bitwise AND, for example. Other denominators don't produce quite so drastic differences. In any case, once you've done the division, the remainder is practically free; the article is basically an illustration of how bad the compilers in question are at spotting this fact. (though not mentioning which compilers and with which flags are affected makes it pretty useless)
[1] It's technically conceivable that a superscalar, microcoded processor might actually detect whether the quotient, the remainder or both are actually used later in the code during the dependency check, and produce 3 different sets of microcode for these situations. I'd be surprised if any actually did this, though.