这是在具有不同任务的相同偏移(C,微优化)问题下快速搜索两个整数中的一些半字节的变体:
任务是在int32中找到预定义的半字节并将其替换为其他半字节.例如,半字节搜索是0x5; 蚕食取代是0xe:
int: 0x3d542753 (input)
^ ^
output:0x3dE427E3 (output int)
Run Code Online (Sandbox Code Playgroud)
可以有另外一对半字节搜索和半字节替换(在编译时已知).
我检查了我的程序,这部分是最热门的地方之一(gprof证明,75%的时间在功能中); 它被称为非常多次(gcov证明).实际上它是嵌套循环的第3或第4循环,运行计数估计为(n ^ 3)*(2 ^ n),n = 18..24.
我当前的代码很慢(我将其重写为函数,但它是来自循环的代码):
static inline uint32_t nibble_replace (uint32_t A) __attribute__((always_inline))
{
int i;
uint32_t mask = 0xf;
uint32_t search = 0x5;
uint32_t replace = 0xe;
for(i=0;i<8;i++) {
if( (A&mask) == search )
A = (A & (~mask) ) // clean i-th nibble
| replace; // and replace
mask <<= 4; search <<= 4; replace …Run Code Online (Sandbox Code Playgroud)