Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplified algorithm for calculating remaining space in a circular buffer?

I was wonder if there is a simpler (single) way to calculate the remaining space in a circular buffer than this?

int remaining = (end > start)
                ? end-start
                : bufferSize - start + end;
like image 840
Dynite Avatar asked Jan 16 '09 14:01

Dynite


2 Answers

If you're worried about poorly-predicted conditionals slowing down your CPU's pipeline, you could use this:

int remaining = (end - start) + (-((int) (end <= start)) & bufferSize);

But that's likely to be premature optimisation (unless you have really identified this as a hotspot). Stick with your current technique, which is much more readable.

like image 127
j_random_hacker Avatar answered Nov 15 '22 19:11

j_random_hacker


Hmmm....

int remaining = (end - start + bufferSize) % bufferSize;

13 tokens, do I win?

like image 41
zaratustra Avatar answered Nov 15 '22 20:11

zaratustra