C++ 如何优化我的程序?
我编写的程序实现了这个公式: Pi=1/n*总和4/1+i-0.5/n^2 程序代码:C++ 如何优化我的程序?,c++,c,optimization,C++,C,Optimization,我编写的程序实现了这个公式: Pi=1/n*总和4/1+i-0.5/n^2 程序代码: #include <iostream> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> using namespace std; const long double PI = double(M_PI); int main(int argc
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
using namespace std;
const long double PI = double(M_PI);
int main(int argc, char* argv[])
{
typedef struct timeval tm;
tm start, end;
int timer = 0;
int n;
if (argc == 2) n = atoi(argv[1]);
else n = 8000;
long double pi1 = 0;
gettimeofday ( &start, NULL );
for(int i = 1; i <= n; i++) {
pi1 += 4 / ( 1 + (i-0.5) * (i-0.5) / (n*n) );
}
pi1/=n;
gettimeofday ( &end, NULL );
timer = ( end.tv_usec - start.tv_usec );
long double delta = pi1 - PI;
printf("pi = %.12Lf\n",pi1);
printf("delta = %.12Lf\n", delta);
cout << "time = " << timer << endl;
return 0;
}
如何以最佳方式呈现它?当此部分中的浮点操作较少时:
for(int i = 1; i <= n; i++) {
pi1 += 4 / ( 1 + (i-0.5) * (i-0.5) / (n*n) );
}
谢谢我建议您阅读这篇优秀的文档: 这也是伟大的,当你没有一个AMD处理器 但如果我是你,我会用
pi1 = M_PI;
哪一个可能是最快的。。。如果您确实对更快的Pi计算算法感兴趣,请参阅维基百科文章:
如果您只想对代码进行微优化,请阅读上述软件优化指南。简单优化示例:
#include <iostream>
#include <cmath>
#include <chrono>
#ifndef M_PI //M_PI is non standard make you sure catch this case
#define M_PI 3.14159265358979323846
#endif
typdef long double float_t;
const float_t PI = double(M_PI);
int main(int argc, char* argv[])
{
int n = argc == 2 ? atoi(argv[1]) : 8000;
float_t pi1=0.0;
//if you can using auto here is a no brainer
std::chrono::time_point start
=std::chrono::system_clock::now();
unsigned n2=n*n;
for(unsigned i = 1; i <= n; i++)
{
pi1 += 4.0 / ( 1.0 + (i-0.5) * (i-0.5) / n2 );
}
pi1/=n;
std::chrono::duration<double> time
=std::chrono::system_clock::now()-start;
float_t delta = pi1 - PI;
std::cout << "pi = " << std::setprecision(12) << pi1
<< "delta = " << std::setprecision(12) << delta
<< "\ntime = " << time.count() << std::endl;
return 0;
}
计算双1/n=1/n;在for循环之外,减少每次迭代除以非循环的成本
在循环内计算双j=i-0.5*1/n
pi1+=4/1+j*j;
这应该更快,并且还可以避免n值较大时的整数溢出。对于更优化的代码,您必须查看生成的代码并使用探查器进行适当的更改。以这种方式优化的代码在具有不同CPU或缓存的计算机上的行为可能会有所不同。。。。避免除法是节省计算时间的好方法。一个想法是:
double nn = n*n;
for(double i = 0.5; i < n; i += 1) {
pi1 += 4 / ( 1 + i * i / nn );
}
但您需要测试它是否与当前代码有任何差异。什么是少操作-一旦构建代码行或指令行?Sergey,您的空格键不起作用吗?为什么要将printf和coutNim结合起来,我的意思是指令您想计算PI还是这个问题与优化有关?用IEEE浮点计算pi或其他级数函数本身就是一门完整的科学。@我也不是一个数学大师,但这样做的最佳方式是将其表示为一个可以在o1中计算的序列,而不是一个循环,但我不确定这是否可行。