/************************************************************ * File: cpi_parallel.c * Purpose: Parallel computation of pi in C with measurement * of the time taken to complete the computation. ************************************************************/ #include #include #include int main(int argc, char *argv[]) { int n = 4800000, myid, numprocs, i; int average, extra, n2, sp, ep; double mypi, pi, h, sum = 0.0, x; clock_t st, et; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); // determine the start and end interval numbers (sp and ep) // for the pi computation average = n / numprocs; extra = n % numprocs; n2 = (myid+1 <= extra) ? average+1 : average; sp = (myid <= extra) ? myid*(average+1)+1 : myid*average+1; ep = sp + n2 - 1; MPI_Barrier(MPI_COMM_WORLD); st = clock(); // get the start time for the pi computation h = 1.0 / n; for(i=sp; i<=ep; i++) { x = h * (i-0.5); sum = sum + 4.0/(1.0+x*x); } mypi = h * sum; MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if(myid == 0) { et = clock(); // get the end time for the pi computation printf("pi: %.16f\n", pi); printf("execution time: %.6f\n", (double)(et-st)/(double)CLOCKS_PER_SEC); } MPI_Finalize(); return 0; }