有没有办法让C代码判断它是否在乘法快速的架构上编译?有一些宏 __FAST_MULT__
或者在这些架构上定义的东西?
例如,假设您正在实现一个函数,通过shift-and-add方法*确定64位整数的汉明权重。有 两个最佳算法:一个需要17个算术运算,而另一个只需要12个,但其中一个是乘法运算。第二种算法因此快30%, 如果 你在硬件上运行,其中乘法所需的时间与加法相同 - 但是在将乘法实现为重复加法的系统上要慢得多。
因此,在编写这样的函数时,能够在编译时检查是否是这种情况并在适当时在两种算法之间切换是有用的:
unsigned int popcount_64(uint64_t x) {
x -= (x >> 1) & 0x5555555555555555; // put count of each 2 bits into those 2 bits
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333); // put count of each 4 bits into those 4 bits
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f; // put count of each 8 bits into those 8 bits
#ifdef __FAST_MULT__
return (x * 0x0101010101010101)>>56; // returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ...
#else // __FAST_MULT__
x += x >> 8; // put count of each 16 bits into their lowest 8 bits
x += x >> 16; // put count of each 32 bits into their lowest 8 bits
x += x >> 32; // put count of each 64 bits into their lowest 8 bits
return x & 0x7f;
#endif // __FAST_MULT__
}
有没有办法做到这一点?
*是的,我知道 __builtin_popcount()
功能;这只是一个例子。