c++ - AND 运算符 + 加法比减法快

标签 c++ assembly execution-time

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

volatile int r = 768;
r -= 511;

volatile int r = 768;
r = (r & ~512) + 1;

组装:

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

结果:

Subtraction time: 141ns   
AND + addition: 53ns

我已经多次运行该代码段并获得一致的结果。
有人能解释一下为什么即使 AND + 加法版本多了一行汇编也会出现这种情况吗?

最佳答案

您关于一个片段比另一个片段更快的断言是错误的。
如果您查看代码:

mov     eax, DWORD PTR [rbp-4]
....
mov     DWORD PTR [rbp-4], eax

您会看到运行时间主要由内存加载/存储决定。
即使在 Skylake 上,这也至少需要 2+2 = 4 个周期。
sub 的 1 个周期或 and bytereg/add full reg 的 3*) 周期简单地消失在内存访问时间中。< br/> 在 Core2 等较旧的处理器上,对同一地址执行加载/存储对最少需要 5 个周期。

很难为如此短的代码序列计时,应注意确保您拥有正确的方法。
您还需要记住 rdstc 在 Intel 处理器上不准确,并且会乱序启动。

If you use proper timing code like :

.... 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.

运行时序代码 a 100x 并取最低循环计数。
现在,您可以在 1 或 2 个周期内进行准确计数。
您还需要为一个空循环计时并减去该循环的时间,以便您可以看到执行相关指令所花费的净时间。

如果你这样做,你会发现 addsub 以完全相同的速度运行,就像自从8086.
这当然也是什么Agner Fog , the Intel CPU manuals , the AMD cpu manuals , 和 just about any other source可用的说。

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

优化代码

sub     DWORD PTR [rbp-4],511

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

关于c++ - AND 运算符 + 加法比减法快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42888338/

相关文章:

c++ - 优化在网格图中查找哈密顿循环的函数?

c++ - 字符串在 vector 数组中被复制

c - 高效内存

c++ - 我的汇编代码有什么问题

sql-server - 查询在 Oracle SQL Developer 中运行很快,但在 SSRS 2008 R2 中运行缓慢

c++ - 指向另一个对象的成员函数的指针

c++ - boost 反序列化错误

assembly - lea 汇编指令

c++ - 直接使用函数参数与创建局部变量