在尝试为我的代码(使用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+,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,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,double(clock() - start)/CLOCKS_PER_SEC); return 0; }
(请注意,printf在这里,以便gcc不优化for循环)
在我的系统上,这可靠地产生以下输出:
u128,took 2.411922s u128,took 1.799805s u64,took 1.797960s u64,took 2.454104s
虽然128位整数行为是有意义的,但我看不清如何使用较少操作的64位循环显着(30%)较慢.
这是一个已知的行为吗?在编写这种循环时尝试从优化中获益的一般规则是什么?
编辑:仅当使用-O3选项编译时才会观察到该行为.
gcc -lstdc++ -O3 -o a main.cpp u128,took 2.413949s u128,took 1.799469s u64,took 1.798278s u64,took 2.453414s gcc -lstdc++ -O2 -o a main.cpp u128,took 2.415244s u128,took 1.800499s u64,took 1.798699s u64,took 1.348133s
解决方法
循环非常紧张,依赖停顿,ALU忙等来发挥主导作用.因此,结果不是可靠的,对其他因素比实际的指令执行更敏感.
注意,25可以与乘法一起并行计算.
PS.我的结果在4970K:
gcc version 5.2.1 20151010 gcc -lstdc++ -O2 -o a a.cpp u128,took 1.346360s u128,took 1.022965s u64,took 1.020189s u64,took 0.765725s
编辑:在对-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>
-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 ....