Re:I've been writing ring buffers wrong all these years
by RBerenguel on Wednesday December 14, 2016 @11:16AM
(#13177096)
Also as mentioned elsewhere in the comments, modulo is expensive, even more for non-powers of 2
Re:I've been writing ring buffers wrong all these years
by pklausler on Wednesday December 14, 2016 @12:51PM
(#13178014)
Modulus by a power of two is cheap. Modulus by a constant is a multiplication by reciprocal and a shift. And if your argument is in [0..2N], mod N is just a conditional subtraction that doesn't even require a branch.
Re:I've been writing ring buffers wrong all these years
by CorvusCrypto on Wednesday December 14, 2016 @01:16PM
(#13178245)
cheap is relative right? I mean a multiplication can be spread over shift and add/sub instructions whereas a mask is just one instruction I think right?
Re:I've been writing ring buffers wrong all these years
by tbirdz on Wednesday December 14, 2016 @02:08PM
(#13178752)
That's only true if your compiler actually outputs a modulus instruction when it sees you doing N % pow2. It really should optimize that into N & (pow2-1) for you, so whether you write the & or the % it will end up running the cheap & version.
0xffffffff % 7 = 3, but (0xffffffff + 1) % 7 = 0.