-
-
Save bbengfort/bf62e3487b9732daebd5 to your computer and use it in GitHub Desktop.
OpenMP parallel integration to compute Pi.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <omp.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#define MAX_THREADS 8 | |
static long steps = 1000000000; | |
double step; | |
int main (int argc, const char *argv[]) { | |
int i,j; | |
double x; | |
double pi, sum = 0.0; | |
double start, delta; | |
step = 1.0/(double) steps; | |
// Compute parallel compute times for 1-MAX_THREADS | |
for (j=1; j<= MAX_THREADS; j++) { | |
printf(" running on %d threads: ", j); | |
// This is the beginning of a single PI computation | |
omp_set_num_threads(j); | |
sum = 0.0; | |
double start = omp_get_wtime(); | |
#pragma omp parallel for reduction(+:sum) private(x) | |
for (i=0; i < steps; i++) { | |
x = (i+0.5)*step; | |
sum += 4.0 / (1.0+x*x); | |
} | |
// Out of the parallel region, finialize computation | |
pi = step * sum; | |
delta = omp_get_wtime() - start; | |
printf("PI = %.16g computed in %.4g seconds\n", pi, delta); | |
} | |
} |
Another implementation:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 8
static long steps = 1000000000;
double step;
int main(int argc, const char* argv[]) {
double pi = 0.0;
double start, delta, sum[NUM_THREADS];
start = omp_get_wtime();
step = 1.0 / (double)steps;
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel
{
double x;
int id, i;
id = omp_get_thread_num();
for (i = id, sum[id] = 0.0; i < steps; i = i + NUM_THREADS) {
x = (i + 0.5) * step;
sum[id] += 4.0 / (1.0 + x * x);
}
}
for (int i = 0; i < NUM_THREADS; i++) {
pi += sum[i] * step;
}
delta = omp_get_wtime() - start;
printf("PI = %.16g computed in %.4g seconds with %d threads.", pi, delta, NUM_THREADS);
}
hello, so why did you define the number of threads "NUM_THREADS" ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, correct me if I wrong but this is limited by the double type, so technically you can't calculate 20 digits.