在什么时候,关于模板方法的部分将/可以由编译器对进行优化?是否会删除无法访问的代码,解包不可缺少的循环?(比特使用无符号int块,整数使用无符号长块)
另外,是否存在c++数据类型,意思是“I是处理器注册中心大小的整数”?
template<size_t bits> class IntegerFactoryImpl : public IntegerFactory<Integer<bits>>{
private:
template<int sizeOfLong, int sizeOfInt> Integer<bits> getOne(const Bits& b) const{
Integer<bits> integer = this->getOne();
size_t roof = (b.blocks() > integer.size()*(sizeOfLong/sizeOfInt))? integer.size()*(sizeOfLong/sizeOfInt) : b.blocks();
for(size_t i = 0; i < roof; ++i){
integer.at(i/(sizeOfLong/sizeOfInt)) = 0;
for(size_t j = 0; j < (sizeOfLong/sizeOfInt); ++j){
if(i % (sizeOfLong/sizeOfInt) == j){
integer.at(i/(sizeOfLong/sizeOfInt)) |= ((unsigned long)b.block(b.blocks()-i-1)) << (sizeOfInt*j);
break;
}
}
}
for(size_t i = roof; i < integer.size()*(sizeOfLong/sizeOfInt); ++i){
if(i % (sizeOfLong/sizeOfInt) == 0){
integer.at(i/(sizeOfLong/sizeOfInt)) = 0;
}
}
return integer;
}
public:
virtual ~IntegerFactoryImpl() throw(){}
virtual Integer<bits> getOne() const{
return Integer<bits>();
}
virtual Integer<bits> getOne(const Bits& b) const{
return this->getOne<sizeof(unsigned long)*8, sizeof(unsigned int)*8>(b);
}
};这段代码(没有模板方法)会有什么区别吗?
template<size_t bits> class IntegerFactoryImpl : public IntegerFactory<Integer<bits>>{
public:
virtual ~IntegerFactoryImpl() throw(){}
virtual Integer<bits> getOne() const{
return Integer<bits>();
}
virtual Integer<bits> getOne(const Bits& b) const{
Integer<bits> integer = this->getOne();
size_t roof = (b.blocks() > integer.size()*((sizeof(unsigned long)/sizeof(unsigned int)))? integer.size()*((sizeof(unsigned long)/sizeof(unsigned int)) : b.blocks();
for(size_t i = 0; i < roof; ++i){
integer.at(i/((sizeof(unsigned long)/sizeof(unsigned int))) = 0;
for(size_t j = 0; j < ((sizeof(unsigned long)/sizeof(unsigned int)); ++j){
if(i % ((sizeof(unsigned long)/sizeof(unsigned int)) == j){
integer.at(i/((sizeof(unsigned long)/sizeof(unsigned int))) |= ((unsigned long)b.block(b.blocks()-i-1)) << ((sizeof(unsigned int)*8)*j);
break;
}
}
}
for(size_t i = roof; i < integer.size()*((sizeof(unsigned long)/sizeof(unsigned int)); ++i){
if(i % ((sizeof(unsigned long)/sizeof(unsigned int)) == 0){
integer.at(i/((sizeof(unsigned long)/sizeof(unsigned int))) = 0;
}
}
return integer;
}
};(编辑:我刚刚发现代码不工作(我修复了它),但原来的问题仍然适用。)
发布于 2013-02-21 22:12:29
对,编译器将优化它在编译时可以计算的内容,如果您有一个只迭代一次的循环(例如,for(i = 0; i < 1; i++),它将完全删除循环)。
至于整数大小,如果使用long或int更好的话,这实际上取决于您试图实现什么。例如,在x86-64中,64位操作需要额外的字节来指示下面的指令是64位指令而不是32位指令。如果编译器使int 64位长,那么代码就会变大(一点点),因此在缓存中不太适合,等等。99%的操作中,16位、32位或64位操作之间没有速度效益,乘法和除法是一些明显的例外--数字越大,在x86-64中除数的时间就越长(实际上,在这个数字中设置的位数会影响乘法时间,我也相信也是除法)。当然,如果您正在使用值来执行位掩码操作等等,那么使用long将给您提供64位操作,这需要一半的操作才能执行相同的操作。这显然是一个优势。因此,在这种情况下使用long是“正确的”,即使它在每个指令中增加了一个额外的字节。
还请记住,int经常用于“较小的数字”,因此对于许多事情,int的额外大小将被浪费掉,占用额外的数据缓存空间等等。因此,int仍然保持32位,以保持大整数数组的大小等在一个合理的大小。
https://stackoverflow.com/questions/15012896
复制相似问题