我正在使用环形缓冲区来保存流音频应用程序的样本。我从 Ken Greenebaum 的《音频轶事 2》书中复制了环缓冲区实现。
在我的代码上运行英特尔的 Vtune 分析器后,它告诉我大部分时间都花在函数 getSamplesAvailable()
和 getSpaceAvailable()
上。
任何人都可以建议我如何优化这些功能吗?
RingBuffer::getSamplesAvailable(void)
{
int count = (mTail - mHead + mSize) % mSize;
return(count);
}
unsigned int RingBuffer::getSpaceAvailable(void)
{
int free = (mHead - mTail + mSize - 1)%mSize;
int underMark = mHighWaterMark - getSamplesAvailable();
int spaceAvailable = min(underMark, free);
return(spaceAvailable);
}
int RingBuffer::push(int value)
{
int status = 1;
if(getSpaceAvailable()) {
// next two operations do NOT have to be atomic!
// do NOT have to worry about collision with _tail
mBuffer[mTail] = value; // store value
mTail = ++mTail % mSize; // increment tail
} else {
status = 0;
}
return(status);
}
int RingBuffer::pop(int *value)
{
int status = 1;
if(getSamplesAvailable()) {
*value = mBuffer[mHead];
mHead = ++mHead % mSize; // increment head
} else {
status = 0;
}
return(status);
}
最佳答案
如果你可以将mSize
设置为2的幂,则可以替换
(mTail - mHead + mSize) % mSize
由
(mTail - mHead) & (mSize-1)
和
(mHead - mTail + mSize - 1) % mSize
由
(mHead - mTail - 1) & (mSize - 1)
关于c++ - 如何提高环形缓冲区代码的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7158254/