浮点数乘法和加法效率有多大差别?
最近遇到一个问题,希望提高我的一个程序的效率,它里面有一个很大的循环,循环体内又有比较多的浮点(double)乘法、加法以及幂运算,执行速度很不怎么样。我以为是幂运算的原因,于是想把它化成查表或者什么的办法,给效率优化下。
接着我做了个测试,得到一个很悲剧的结果。。。
是这样的,我做了10亿次循环,里面分别填入求幂、乘法、加法(double)、加法(int),结果发现除了Debug版本求幂执行时间明显超过其他外,其余运算时间差异太小,release下更是接近。
有人给我解释一下吗?谢谢
代码:
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cstring>
#include <cstdio>
int main(int argc, char* argv[])
{
int m = 28;
int n = 28;
clock_t start, end;
const int counts = 100000000;
start = clock();
for (long long i=0; i<counts; ++i)
{
double xx = pow(1.9, -3.3);
}
end = clock();
printf_s("Time: %f", (double)(end - start)/CLOCKS_PER_SEC);
start = clock();
for (long long i=0; i<counts; ++i)
{
double xx = 3.3*1.9;
}
end = clock();
printf_s("Time: %f", (double)(end - start)/CLOCKS_PER_SEC);
double table[100];
memset(table, 0, 100*sizeof(double));
start = clock();
for (long long i=0; i<counts; ++i)
{
double xx = table[10];
}
end = clock();
printf_s("Time: %f", (double)(end - start)/CLOCKS_PER_SEC);
start = clock();
for (long long i=0; i<counts; ++i)
{
double xx = 1.3+3.1;
}
end = clock();
printf_s("Time: %f", (double)(end - start)/CLOCKS_PER_SEC);
start = clock();
for (long long i=0; i<counts; ++i)
{
int x = 18+21;
}
end = clock();
printf_s("Time: %f", (double)(end - start)/CLOCKS_PER_SEC);
system("pause");
return 0;
}