我在我的代码中使用了一种名为BitStream的数据流,其中包含一个read_bit()
函数。该函数被频繁调用(单个数据流中超过10亿次)。以下是BitStream结构的示例:
typedef struct BitStream {
unsigned char* data;
unsigned int size;
unsigned int currentByte;
unsigned char buffer;
unsigned char bitsInBuffer;
} BitStream;
而read_bit()
函数定义如下:
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秒钟。 因此,我使用了该函数而非使用掩码
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;
}
我显然也已经改变了相应的写入函数。