#include #include #include #include #include #include #include #include using namespace std; const long long DEFAULT_LIMIT = 1'000'000; class comma_numpunct : public std::numpunct { protected: virtual char do_thousands_sep() const { return ','; } virtual std::string do_grouping() const { return "\03"; } }; int main(int argc, char * argv[]) { long double sum = 0; long double term; long long limit = DEFAULT_LIMIT; timespec beginTS, endTS; clock_t start, stop; int sign = 1; int threads = 0; long long i; i = 1; while (i < argc) { if ( !strcmp("-l",argv[i]) and argv[i+1] != nullptr) { i++; limit= atoll(argv[i]); i++; } else if ( !strcmp("-p",argv[i]) and argv[i+1] != nullptr) { i++; threads = atoi(argv[i]); i++; } else { cout << "Error: " << argv[i] << endl; i++; } } if (limit < 0) { limit = DEFAULT_LIMIT; } if (threads > 0) { omp_set_num_threads(threads); } cout << endl; locale comma_locale(locale(), new comma_numpunct()); cout.imbue(comma_locale); cout << "The limit is " << limit << endl; cout << setprecision(20); start = clock(); clock_gettime(CLOCK_REALTIME, &beginTS); #pragma omp parallel #pragma omp master { cout << "Using " << omp_get_num_threads() << " threads " << endl; } #pragma omp parallel { long long v; #pragma omp for reduction(+:sum) for(i=0;i<= limit;i++) { //cout << omp_get_thread_num() << " has " << i << endl; if (i%2==0) { sign = 1; } else { sign = -1; } v = 2*i+1; term = sign * 4.0/(long double)(v); sum += term; } } stop = clock(); clock_gettime(CLOCK_REALTIME, &endTS); cout << endl; cout << "Pi = " << sum << endl; cout << "Error: " << fabsl(M_PIl - sum) << endl; cout << endl; cout << setprecision(5); cout << "Process time: " << (stop-start)/double(CLOCKS_PER_SEC) << " seconds" << endl; time_t sec = endTS.tv_sec - beginTS.tv_sec; long nsec = endTS.tv_nsec - beginTS.tv_nsec; if (nsec < 0) { nsec+= 1'000'000'000; } nsec /=10000000; cout << "Wall clock time: " << sec << "." << nsec << " seconds" << endl; cout << endl; return 0; }