AND运算符+加法比减法更快

Que*_*est 0 c++ assembly execution-time

我已经测量了以下代码的执行时间:

volatile int r = 768;
r -= 511;

volatile int r = 768;
r = (r & ~512) + 1;
Run Code Online (Sandbox Code Playgroud)

部件:

mov     eax, DWORD PTR [rbp-4]
sub     eax, 511
mov     DWORD PTR [rbp-4], eax

mov     eax, DWORD PTR [rbp-4]
and     ah, 253
add     eax, 1
mov     DWORD PTR [rbp-4], eax
Run Code Online (Sandbox Code Playgroud)

结果:

Subtraction time: 141ns   
AND + addition: 53ns
Run Code Online (Sandbox Code Playgroud)

我已经多次运行代码片段并且结果一致.
有人可以解释一下,为什么会出现这种情况,甚至还有一个AND +添加版本的组装线?

Joh*_*ica 5

你断言一个片段比另一个片段更快是错误的.
如果你看代码:

mov     eax, DWORD PTR [rbp-4]
....
mov     DWORD PTR [rbp-4], eax
Run Code Online (Sandbox Code Playgroud)

您将看到运行时间由加载/存储到内存的主导.
即使在Skylake上,这也只需要2 + 2 = 4个周期.
这个sub或3 *)循环的1个周期and bytereg/add full reg简单地消失在内存访问时间中.
在较旧的处理器(如Core2)上,最少需要5个周期才能将加载/存储对连接到同一地址.

很难计算出如此短的代码序列,应该注意确保您拥有正确的方法.
您还需要记住,rdstc在英特尔处理器上并不准确,并且无法启动.

如果您使用适当的时序代码,如:

.... x 100,000    //stress the cpu using integercode in a 100,000 x loop to ensure it's running at 100%
cpuid             //serialize instruction to make sure rdtscp does not run early.
rdstcp            //use the serializing version to ensure it does not run late   
push eax
push edx
mov reg1,1000*1000   //time a minimum of 1,000,000 runs to ensure accuracy
loop:
...                  //insert code to time here
sub reg1,1           //don't use dec, it causes a partial register stall on the flags.
jnz loop             //loop
//kernel mode only!
//mov eax,cr0          //reading and writing to cr0 serializes as well.
//mov cr0,eax
cpuid                //serialization in user mode.
rdstcp               //make sure to use the 'p' version of rdstc.
push eax
push edx
pop 4x               //retrieve the start and end times from the stack.
Run Code Online (Sandbox Code Playgroud)

将定时代码运行100倍并取最低循环次数.
现在,您将获得1到2个周期内的准确计数.
您还需要为空循环计时并减去时间,以便您可以看到执行感兴趣的指令所花费的净时间.

如果你这样做,你会发现,addsub以完全相同的速度运行,就像它每天在x86/x64 CPU的/没有因为8086
这,当然,也正是昂纳雾,英特尔CPU的手册,在AMD cpu手册,以及几乎 任何其他可用资源说明.

*)and ah,value需要1个周期,然后由于部分寄存器写入而CPU停止1个周期,并且add eax,value需要另一个周期.

优化的代码

sub     DWORD PTR [rbp-4],511
Run Code Online (Sandbox Code Playgroud)

如果您不需要在其他地方重用该值,可能会更快,延迟在5个周期缓慢,但倒数吞吐量是1个周期,这比您的任何一个版本要好得多.