循环缓冲区优化

时间:2014-04-05 09:47:58

标签: c++ bit-manipulation circular-buffer

我有一个大小为2的循环缓冲区。我的目标是优化其工作。这是简短的代码:

class CircularBuffer
{
public:
  CircularBuffer(unsigned int bufferSize); // align this size to power of 2
  void read(char * dst, unsigned int bytes);
  void write(char * src, unsigned int bytes);
private:
  unsigned int m_readOffset;
  unsigned int m_writeOffset;
  std::vector<char> m_buffer;
};

CircularBuffer::write(char * src, unsigned int bytes)
{
  int dif = bytes - (m_buffer.size() - m_writeOffset);
  unsigned int mask = ~(dif >> 31); // 0 or 0xFFFFFFFF
  dif &= mask; // now i know how much bytes i need to put at the beginning of the buffer
  memcpy(&m_buffer[m_writeOffset], src, bytes - dif);
  memcpy(&m_buffer[0], src + bytes - dif, dif);
  m_writeOffset = (m_wirteffset + bytes) & (m_buffer.size() -1);
}

m_writeOffset表示已经放入缓冲区的字节数。 正如你所看到的那样,我摆脱了if(保持buff&lt; srcSize中的大小)等条件,并使用位掩码计算writeOffset。

但我的主程序员告诉我,有一种方法可以计算缓冲区末尾要放多少字节以及使用按位运算在开始时放入多少字节,因为缓冲区的大小是2的幂。任何建议?

1 个答案:

答案 0 :(得分:0)

您已经在使用无符号变量来跟踪队列的正面和背面(这很好);只需在每次写入(入队)操作时递增m_writeOffset,并在每次读取(出列)操作时递增m_readOffset。计算缓冲区元素的剩余量非常简单:

// returns the distance between m_readOffset and m_writeOffset
// (the count of the actual buffer elements):
uint32_t CircularBuffer::Size()
{
    if (m_readOffset < m_writeOffset)
    {
        return (m_writeOffset - m_readOffset);
    }
    else
    {
        return (m_readOffset - m_writeOffset);
    }
} 

查看基本2循环队列的STL模板实现的源代码:

CircularQueue.h

CircularQueue.cpp