计算平方根的速度有多慢(多少周期)?这是在一门分子动力学课程中出现的,其中效率很重要,取不必要的平方根对算法的运行时间有明显的影响。
发布于 2011-10-11 20:48:15
从Agner Fog的指令表中:
在Core2 65 and上,根据值和精度位的不同,FSQRT需要9到69毫升(具有几乎相等的倒数吞吐量)。作为比较,FDIV需要9到38毫升(几乎相等的倒数吞吐量),FMUL需要5(配方吞吐量= 2),FADD需要3(配方吞吐量= 1)。SSE的性能差不多,但看起来更快,因为它不能做80位的数学运算。SSE具有超快的近似倒数和近似倒数sqrt。
在Core2 45 21上,除法和平方根变快,FSQRT6~20cc,FDIV6~21cc,FADD值和FMUL值无变化。同样,上交所的表现也大致相同。
您可以从his website获取包含此信息的文档。
发布于 2011-10-11 17:42:25
平方根大约比使用-O2
的加法慢4倍,或者不使用-O2
的情况下大约慢13倍。在网上的其他地方,我发现了50-100个周期的估计,这可能是真的,但它并不是一个非常有用的相对成本度量,所以我把下面的代码放在一起进行相对度量。如果您在测试代码中发现任何问题,请告诉我。
下面的代码在Windows7操作系统下的英特尔酷睿i3上运行,并在DevC++ (使用GCC)中编译。您的里程可能会有所不同。
#include <cstdlib>
#include <iostream>
#include <cmath>
/*
Output using -O2:
1 billion square roots running time: 14738ms
1 billion additions running time : 3719ms
Press any key to continue . . .
Output without -O2:
10 million square roots running time: 870ms
10 million additions running time : 66ms
Press any key to continue . . .
Results:
Square root is about 4 times slower than addition using -O2,
or about 13 times slower without using -O2
*/
int main(int argc, char *argv[]) {
const int cycles = 100000;
const int subcycles = 10000;
double squares[cycles];
for ( int i = 0; i < cycles; ++i ) {
squares[i] = rand();
}
std::clock_t start = std::clock();
for ( int i = 0; i < cycles; ++i ) {
for ( int j = 0; j < subcycles; ++j ) {
squares[i] = sqrt(squares[i]);
}
}
double time_ms = ( ( std::clock() - start ) / (double) CLOCKS_PER_SEC ) * 1000;
std::cout << "1 billion square roots running time: " << time_ms << "ms" << std::endl;
start = std::clock();
for ( int i = 0; i < cycles; ++i ) {
for ( int j = 0; j < subcycles; ++j ) {
squares[i] = squares[i] + squares[i];
}
}
time_ms = ( ( std::clock() - start ) / (double) CLOCKS_PER_SEC ) * 1000;
std::cout << "1 billion additions running time : " << time_ms << "ms" << std::endl;
system("PAUSE");
return EXIT_SUCCESS;
}
发布于 2014-03-19 08:51:38
平方根需要几个周期,但如果不在缓存中,则访问内存需要更多的数量级。因此,试图通过从内存获取预先计算的结果来避免计算实际上可能会损害性能。
很难抽象地说你是否会有所收获,所以如果你想确定,试着对这两种方法进行基准测试。
下面是微软的编译器开发人员Eric Brummer关于这个问题的一个很棒的演讲:http://channel9.msdn.com/Events/Build/2013/4-329
https://stackoverflow.com/questions/7724061
复制相似问题