Skip to content

Instantly share code, notes, and snippets.

@bbengfort
Created October 17, 2015 12:59
Show Gist options
  • Save bbengfort/bf62e3487b9732daebd5 to your computer and use it in GitHub Desktop.
Save bbengfort/bf62e3487b9732daebd5 to your computer and use it in GitHub Desktop.
OpenMP parallel integration to compute Pi.
#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);
}
}
@AKCen
Copy link

AKCen commented Jul 5, 2019

Hi, correct me if I wrong but this is limited by the double type, so technically you can't calculate 20 digits.

@songquanpeng
Copy link

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);
}

@iR00i
Copy link

iR00i commented Nov 26, 2020

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