#include <stdio.h>
#include <omp.h>
#define MAX_THREADS 4
static long num_steps = 100000000;
double step;
double f(double x){
return(4.0/(1.0+x*x));
}
int main ()
{
int j;
double pi, full_sum = 0.0;
double start_time, run_time;
double sum[MAX_THREADS];
step = 1.0/(double) num_steps;
for (j=1;j<=MAX_THREADS ;j++) {
omp_set_num_threads(j);
full_sum = 0.0;
start_time = omp_get_wtime();
#pragma omp parallel
{
int i;
int id = omp_get_thread_num();
int numthreads = omp_get_num_threads();
int steps_per_thread=num_steps/numthreads;
double x;
double partial_sum = 0;
double start_position=id*(1.0/numthreads);
for (i=0;i< steps_per_thread; i+=1) {
/*Block 1*/
partial_sum = partial_sum+(f((i+0.5)*step+start_position));
/*Block 2
x=(i+0.5)*step+start_position;
partial_sum = partial_sum+f(x); */
}
#pragma omp critical /*Only be executed on one thread at a time.*/
full_sum += partial_sum;
}
pi = step * full_sum;
run_time = omp_get_wtime() - start_time;
printf("\n pi is %f in %f seconds %d threads \n ",pi,run_time,j);
}
}
Block 1
Block 2