计算循环缓冲区中剩余空间的简化算法? [英] 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;
推荐答案
如果你担心预测不佳的条件你可以使用这个:
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.
这篇关于计算循环缓冲区中剩余空间的简化算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文