我在我的代码中使用了某种具有 -function 的read_bit()
BitStream。这个函数被非常频繁地调用(在单个流中超过 10 亿次)。这是 struct BitStream 的样子:
typedef struct BitStream {
unsigned char* data;
unsigned int size;
unsigned int currentByte;
unsigned char buffer;
unsigned char bitsInBuffer;
} BitStream;
并且read_bit()
-function 定义如下:
unsigned char bitstream_read_bit(BitStream* stream, unsigned long long bitPos) {
unsigned int byte = bitPos / 8;
unsigned char byteVal = stream->data[byte];
unsigned char mask = 128 >> (bitPos & 7);
if (mask & byteVal) {
return 1;
} else {
return 0;
}
}
现在,我通过反复试验发现这条线unsigned char mask = 128 >> (bitPos & 7);
非常慢。有什么方法可以加快检查速度吗?我已经尝试使用一个数组来索引 8 个不同的可能掩码,但这并不快(我认为是由于内存访问)。
编辑:在过去的一周里,我尝试了很多答案并进行了很多基准测试,但性能并没有太大的提升。通过颠倒比特流中的比特顺序,我最终设法获得了 10 秒的改进。因此,我没有使用 mask 128 >> (bitPos & 7)
,而是使用了以下功能:
unsigned char bitstream_read_bit_2(BitStream* stream, const unsigned long long bitPos) {
unsigned int byte = (unsigned int) (bitPos / 8);
unsigned char byteVal = stream->data[byte];
unsigned char mod = bitPos & 7;
return (byteVal & (1 << mod)) >> mod;
}
我显然也改变了相应的写功能。