gpt4 book ai didi

c++ - GCC 优化 : how can less operations be slower?

转载 作者:可可西里 更新时间:2023-11-01 16:06:31 27 4
gpt4 key购买 nike

在尝试对我的代码的某些选项进行基准测试时(使用或不使用 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

最佳答案

循环非常紧凑,以至于依赖停顿、ALU 繁忙等开始发挥作用并控制时序。因此,结果不可靠,并且对实际指令执行以外的其他因素更敏感。

请注意,+25 可以与乘法并行计算。


附言。我在 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 生成矢量化代码,而循环具有严重的依赖性,无法从矢量化中获取值(value)。它实际上生成了更复杂的代码,因此需要更长的时间。

关于c++ - GCC 优化 : how can less operations be slower?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37067144/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com