@BravoWA
2015-12-27T13:09:06.000000Z
字数 935
阅读 1192
未分类
#include <iostream>
#include "omp.h"
using namespace std;
/*
Exercise 2, Serial PI program to parallel PI program
*/
static long num_steps = 1000000;
double step;
void main()
{
int i;
double x, pi, sum = 0;
double time_start, time_end;
step = 1.0/(double)num_steps;
//Serial version
time_start = omp_get_wtime();
for (i = 0; i < num_steps; i++)
{
x = (i+0.5)*step;
sum = sum + 4.0/(1.0+x*x);
}
pi = step*sum;
time_end = omp_get_wtime();
cout << scientific << "Calculated results = " << pi << endl;
cout << "Calculated times = " << (time_end - time_start)
<< endl;
// Parallel version
sum = 0.0;
omp_set_num_threads(4);
time_start = omp_get_wtime();
#pragma omp parallel for reduction(+:sum)
for (i = 0; i < num_steps; i++)
{
x = (i+0.5)*step;
sum = sum + 4.0/(1.0+x*x);
}
pi = step*sum;
time_end = omp_get_wtime();
cout << "Calculated results = " << pi << endl;
cout << "Calculated times = " << (time_end - time_start)
<< endl;
cin.get();
return;
}
VS2012结果:
Calculated results = 3.141593e+000
Calculated times = 4.392572e-002
Calculated results = 3.141593e+000
Calculated times = 3.620780e-002