Re:I've been writing ring buffers wrong all these years
by jstimpfle on Wednesday December 14, 2016 @10:25AM
(#13176597)
Don't use a modulo then. Use subtraction.
Re:I've been writing ring buffers wrong all these years
by dllthomas on Wednesday December 14, 2016 @10:57AM
(#13176898)
Subtraction requires a branch, which could be worse (or not) depending on architecture.
Re:I've been writing ring buffers wrong all these years
by pklausler on Wednesday December 14, 2016 @12:45PM
(#13177951)
Oh, come on, you don't need a branch to do a conditional subtraction. Reify the condition to 0/1 and use multiplication, or use AND with a two's complement of the condition.
Re:I've been writing ring buffers wrong all these years
by cksk on Thursday December 15, 2016 @11:44AM
(#13185891)
OK, my bit twiddling knowledge is weak, my google skills are weaker still, and now I'm curious: what does "AND with a two's complement of the condition" mean, exactly?
Re:I've been writing ring buffers wrong all these years
by pklausler on Thursday December 15, 2016 @12:41PM
(#13186424)
x -= N & -(x >= N);
Re:I've been writing ring buffers wrong all these years
by cksk on Thursday December 15, 2016 @01:20PM
(#13186767)
Ohh, nice, I get it now. Thanks a lot!
Re:I've been writing ring buffers wrong all these years
by avocad on Wednesday December 14, 2016 @03:42PM
(#13179468)
Thanks! This AND trick is great. Actually makes me want to go back to assembly-level programming.
Re:I've been writing ring buffers wrong all these years
by dllthomas on Wednesday December 14, 2016 @02:30PM
(#13178929)
Good point!
Re:I've been writing ring buffers wrong all these years
by jnordwick on Wednesday December 14, 2016 @04:38PM
(#13179894)
The branch will be properly predicted every time except for when it wraps. This should be faster than any of the alternatives.
Last time I checked, the operation cost was 26k cycles on my PIC.
Using a 2^n + mask made my queue perform 10 times faster (if not more).