#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
int main() {
for (long n=2*pow(10,8); n<2*pow(10,12); n*=10)
{
double pi_approx;
float total;
clock_t begin, end;
double sum = 0.0;
double factor = 1.0;
begin = clock();
for (int k=0; k<n; k++, factor=-factor) {
sum += factor/(2*k+1);
}
pi_approx = 4 * sum;
end = clock();
total = (float)(end-begin)*1000 / CLOCKS_PER_SEC;
cout.width(14);
cout.setf(ios::left);
cout.precision(14);
cout<<n<<"pi: "<<pi_approx<<" time:"<<total<<"ms"<<endl;
}
}
程式如上, 計算不同規模下pi的值, 并計算所有時間, 結果發現, 為什么規模越大, 耗時反而減少了?
[root@centos7 ~]# g++ pthred_chuanxing.cpp -o pthread_chuanxing -O2
[root@centos7 ~]# ./pthread_chuanxing
200000000 pi: 3.1415926485894 time:360ms
2000000000 pi: 3.1415926585052 time:3569.9997558594ms
20000000000 pi: 3.141592652102 time:1200ms
200000000000 pi: 3.1415926500684 time:520ms
當我直接執行2000000000時, 卻怎么也出不來結果
求大佬解答!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/81056.html
標籤:C++ 語言
