#include <stdio.h> #include <string.h> #include <sys/types.h> #include "mpi.h" double f(a) double a; { return (4.0 / (1.0 + a*a)); } int main ( int argc, char **argv ) { int pool_size, my_rank, host_rank, destination, source, node_name_length, *host_rank_ptr, found_flag, int_buffer[BUFSIZ]; char char_buffer[BUFSIZ], my_node_name[BUFSIZ], console_name[BUFSIZ], host_name[BUFSIZ]; MPI_Status status; boolean_t i_am_the_master = B_FALSE; #include "preamble.c" { int n, i; double mypi, pi, h, sum, x, a, start_time, end_time, communication_time, computation_time; while (1) { if (i_am_the_master) { printf("Enter the number of intervals: (0 quits) "); scanf("%d",&n); } start_time = MPI_Wtime(); MPI_Bcast(&n, 1, MPI_INT, host_rank, MPI_COMM_WORLD); end_time = MPI_Wtime(); communication_time = end_time - start_time; if (n == 0) break; else { start_time = MPI_Wtime(); h = 1.0 / (double) n; sum = 0.0; for (i = my_rank + 1; i <= n; i += pool_size) { x = h * ((double)i - 0.5); sum += f(x); } mypi = h * sum; end_time = MPI_Wtime(); computation_time = end_time - start_time; start_time = MPI_Wtime(); MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, host_rank, MPI_COMM_WORLD); end_time = MPI_Wtime(); communication_time = communication_time + end_time - start_time; if (i_am_the_master) { printf("pi is approximately %.16f\n", pi); printf("computation time %.16f\n", computation_time); printf("communication time %.16f\n", communication_time); } } } } MPI_Finalize (); }