/* Seriel Code */
#include
#include
#include
static long num_steps = 500000000;
double step;
int main()
{
int i;
double x, pi, sum = 0.0;
struct timeval start, finish;
double diffsec,diffusec;
gettimeofday(&start,NULL);
step = 1.0/(double) num_steps;
for (i=0;i< num_steps; i++){
x = (i+0.5)*step;
sum = sum + 4.0/(1.0+x*x);
}
pi = step * sum;
gettimeofday(&finish,NULL);
diffsec=(double)finish.tv_sec-start.tv_sec;
diffusec=(double)(finish.tv_usec-start.tv_usec)/(double)1000000;
diffsec+=diffusec;
printf("Cost time=%f second ,pi=%20.14lf\n",diffsec,pi);
return 0;
}
/*parallel program with openmp*/
#include
#include
#include
#include
static long num_steps = 500000000;
double step;
#define NUM_THREADS 2
int main()
{
int i;
double x, sum, pi=0.0;
struct timeval start, finish;
double diffsec,diffusec;
gettimeofday(&start,NULL);
step = 1.0/(double) num_steps;
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel for private(x) reduction(+:sum)
for (i=0;i<= num_steps; i++){
x = (i+0.5)*step;
sum = sum + 4.0/(1.0+x*x);
}
gettimeofday(&finish,NULL);
diffsec=(double)finish.tv_sec-start.tv_sec;
diffusec=(double)(finish.tv_usec-start.tv_usec)/(double)1000000;
diffsec+=diffusec;
printf("Cost time=%f second ,pi=%20.14lf\n",diffsec,sum/num_steps);
return 0;
}
编译方法:gcc -fopenmp -o parallel openmp.c