在尝试为我的代码测试某些选项时(使用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;
}
(请注意,printf在这里,以便gcc不会优化for循环) 在我的系统上,这可靠地产生以下输出:
u128, +25, took 2.411922s
u128, no+, took 1.799805s
u64 , +25, took 1.797960s
u64 , no+, took 2.454104s
虽然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
答案 0 :(得分:8)
循环太紧,依赖性失速,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
编辑:在查看-O2
和-O3
上的反汇编后,主要区别在于代码生成。 (由于上述原因,在不同的测试机器/环境中仍然保持-O2,产生的结果略有不同)
<强> -O2:强>
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>
<强> -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
....
O3生成矢量化代码,而循环具有很强的依赖性,无法从矢量化中获取值。它实际上产生了更复杂的代码,因此具有更长的时间。
答案 1 :(得分:0)
您需要测量运行时实际发生的事情才能确定。 正如Calvin中提到his answer一样,处理器内部会发生很多事情,这会影响循环的最终时间。
您可以使用PAPI或Intel's brilliant tools来执行测量。英特尔的工具价格昂贵,但您可以免费试用30天。它们比PAPI更容易使用。