Dai*_*Dai 10 c++ optimization gcc
在尝试为我的代码测试一些选项时(使用128位整数)我观察到一种我无法理解的行为.有人可以对此有所了解吗?
#include <stdio.h>
#include <stdint.h>
#include <time.h>
int main(int a, char** b)
{
printf("Running tests\n");
clock_t start = clock();
unsigned __int128 t = 13;
for(unsigned long i = 0; i < (1UL<<30); i++)
t += 23442*t + 25;
if(t == 0) printf("0\n");
printf("u128, +25, took %fs\n", double(clock() - start)/CLOCKS_PER_SEC);
start = clock();
t = 13;
for(unsigned long i = 0; i < (1UL<<30); i++)
t += 23442*t;
if(t == 0) printf("0\n");
printf("u128, no+, took %fs\n", double(clock() - start)/CLOCKS_PER_SEC);
start = clock();
unsigned long u = 13;
for(unsigned long i = 0; i < (1UL<<30); i++)
u += 23442*u + 25;
if(u == 0) printf("0\n");
printf("u64 , +25, took %fs\n", double(clock() - start)/CLOCKS_PER_SEC);
start = clock();
u = 13;
for(unsigned long i = 0; i < (1UL<<30); i++)
u += 23442*u;
if(u == 0) printf("0\n");
printf("u64 , no+, took %fs\n", double(clock() - start)/CLOCKS_PER_SEC);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
(请注意,printf在这里,以便gcc不会优化for循环)在我的系统上,这可靠地产生以下输出:
u128, +25, took 2.411922s
u128, no+, took 1.799805s
u64 , +25, took 1.797960s
u64 , no+, took 2.454104s
Run Code Online (Sandbox Code Playgroud)
虽然128位整数行为是有意义的,但我没有看到具有较少操作的64位循环如何显着(30%)较慢.
这是一种已知的行为吗?在编写此类循环时尝试从此优化中受益的一般规则是什么?
编辑:仅在使用-O3选项进行编译时才会观察到该行为.
gcc -lstdc++ -O3 -o a main.cpp
u128, +25, took 2.413949s
u128, no+, took 1.799469s
u64 , +25, took 1.798278s
u64 , no+, took 2.453414s
gcc -lstdc++ -O2 -o a main.cpp
u128, +25, took 2.415244s
u128, no+, took 1.800499s
u64 , +25, took 1.798699s
u64 , no+, took 1.348133s
Run Code Online (Sandbox Code Playgroud)
循环是如此紧密,以至于依赖性失速,ALU忙等起作用并控制时间.因此,结果对于除实际指令执行之外的其他因素不可靠且更敏感.
注意,+ 25可以与乘法并行计算.
PS.我在4970K上的结果:
gcc version 5.2.1 20151010
gcc -lstdc++ -O2 -o a a.cpp
u128, +25, took 1.346360s
u128, no+, took 1.022965s
u64 , +25, took 1.020189s
u64 , no+, took 0.765725s
Run Code Online (Sandbox Code Playgroud)
编辑:照顾到拆机上-O2和-O3,主要的区别是然后在代码生成.(上述原因仍然在不同的测试机器/环境中保持-O2,产生略微不同的结果)
-02:
400618: 48 69 d2 93 5b 00 00 imul $0x5b93,%rdx,%rdx
40061f: 48 83 e8 01 sub $0x1,%rax
400623: 75 f3 jne 400618 <_Z4testv+0x18>
Run Code Online (Sandbox Code Playgroud)
-O3:
400628: 66 0f 6f d9 movdqa %xmm1,%xmm3
40062c: 83 c0 01 add $0x1,%eax
40062f: 66 0f 6f c1 movdqa %xmm1,%xmm0
400633: 66 0f f4 cc pmuludq %xmm4,%xmm1
400637: 3d 00 00 00 20 cmp $0x20000000,%eax
40063c: 66 0f f4 da pmuludq %xmm2,%xmm3
400640: 66 0f 73 d0 20 psrlq $0x20,%xmm0
....
Run Code Online (Sandbox Code Playgroud)
O3生成矢量化代码,而循环具有很强的依赖性,无法从矢量化中获取值.它实际上产生了更复杂的代码,因此具有更长的时间.