gpt4 book ai didi

c++ - 读取位性能

转载 作者:太空狗 更新时间:2023-10-29 23:09:17 25 4
gpt4 key购买 nike

我正在编写一个帮助程序类,我打算将其用于从数据 block 中反向读取位。

我尝试进行优化,其中使用“rol”指令来屏蔽数据。然而,令我惊讶的是,这实际上比在每次访问期间创建一个新的位掩码要慢。

class reverse_bit_reader
{
public:
static const size_t bits_per_block = sizeof(unsigned long)*8;
static const size_t high_bit = 1 << (bits_per_block-1);

reverse_bit_reader(const void* data, size_t size)
: data_(reinterpret_cast<const unsigned long*>(data))
, index_(size-1)
{
// Bits are stored in left to right order, potentially ignore the last bits
size_t last_bit_index = index_ % bits_per_block;
bit_mask_ = high_bit >> (last_bit_index+1);
if(bit_mask_ == 0)
bit_mask_ = high_bit;
}

bool next_bit1()
{
return get_bit(index_--);
}

bool next_bit2() // Why is next_bit1 faster?
{
__asm // Rotate bit_mask.
{
mov eax, [ecx+0];
rol eax, 1;
mov [ecx+0], eax;
}
return data_[index_-- / bits_per_block] & bit_mask_;
}

bool eof() const{return index_ < 0;}
private:

bool get_bit(size_t index) const
{
const size_t block_index = index / bits_per_block;
const size_t bit_index = index % bits_per_block;
const size_t bit_mask = high_bit >> bit_index;
return data_[block_index] & bit_mask;
}

unsigned long bit_mask_;
int index_;
const unsigned long* data_;
};

谁能解释为什么 next_bit1 比 next_bit2 快?

最佳答案

如果您要从 long 中按顺序读取位,从最高有效位开始,并且您希望它尽可能快,您可以按照这些思路做些事情吗?

#define GETBIT ((theBit = (theLong < 0)), (theLong <<= 1), theBit)

关于c++ - 读取位性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5779133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com