Select Git revision
mpi_pi_cpu.c 1.54 KiB
/*
* mpipi.c
* Neil Gershenfeld 2/5/11
* Erik Strand 3/6/2021
* use MPI to evaluate pi by summation
*/
#include <stdio.h>
#include <mpi.h>
#include <sys/time.h>
// number of terms evaluated by each process
#define NPTS 250000000
void main(int argc, char** argv) {
// variables used by all ranks
int rank;
long unsigned int i, istart, iend;
double sum, pi;
// variables used only by rank 0
unsigned long int start_time, end_time;
struct timeval start, end;
int nproc;
unsigned long int total_terms;
double mflops;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
MPI_Comm_size(MPI_COMM_WORLD, &nproc);
total_terms = nproc;
total_terms *= NPTS;
gettimeofday(&start, NULL);
}
istart = (long unsigned int)NPTS * rank + 1;
iend = istart + NPTS;
sum = 0.0;
for (i = istart; i <= iend; ++i) {
sum += 0.5 / ((i - 0.75) * (i - 0.25));
}
MPI_Reduce(&sum, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
gettimeofday(&end, NULL);
start_time = start.tv_sec * 1e6 + start.tv_usec;
end_time = end.tv_sec * 1e6 + end.tv_usec;
mflops = (double)nproc * NPTS * 5.0 / (end_time - start_time);
printf("processes = %d, terms per process = %ldM, total terms = %ldM\n", nproc, NPTS / 1000000, total_terms / 1000000);
printf("time = %fs, estimated GFlops = %f\n", (end_time - start_time) / 1.0e6, mflops / 1000);
printf("pi ~ %f\n", pi);
}
MPI_Finalize();
}