/* ===================================================== MPI example: find max and min in array ===================================================== */ #include #include #include #include struct timeval start_time, stop_time; int elapsed; #define MAX 100000000 int num_procs; double x[MAX]; int main(int argc, char *argv[]) { char *s; int i, n; int start, stop; int myid; double my_min, others_min[10]; double my_max, others_max[10]; MPI_Request rq_min[10]; MPI_Request rq_max[10]; MPI_Init(&argc,&argv); // Initialize MPI_Comm_size(MPI_COMM_WORLD, &num_procs); // Get # processors MPI_Comm_rank(MPI_COMM_WORLD, &myid); // Get my rank (id) /* ------------------------- Generate random number ------------------------- */ for (i = 0; i < MAX; i++) x[i] = random()/(double)1147483648; if ( myid == 0 ) cout << "Using " << num_procs << " processes..." << endl << endl; gettimeofday(&start_time, NULL); /* ******************************************************************* */ /* -------------------------------------- Find the min. among my numbers The min is stored in min[s] -------------------------------------- */ n = MAX/num_procs; start = myid * n; if ( myid != (num_procs-1) ) { stop = start + n; } else { stop = MAX; } my_min = x[start]; for (i = start+1; i < stop; i = i + n ) { if ( x[i] < my_min ) my_min = x[i]; } /* ******************************************************************* */ if ( myid == 0 ) { cout << "Done... Now collecting output from others" << endl; /* ---------------------------------------------- Start getting the min from others..... ---------------------------------------------- */ for (i = 1; i < num_procs; i++) { MPI_Irecv(&others_min[i], 1, MPI_DOUBLE,i,0, MPI_COMM_WORLD, &rq_min[i]); } } else { MPI_Isend(&my_min, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &rq_min[0]); } /* ----------------------------------------------- ----------------------------------------------- Now find the max ----------------------------------------------- ----------------------------------------------- */ my_max = x[start]; for (i = start+1; i < stop; i = i + n ) { if ( x[i] > my_max ) my_max = x[i]; } /* ******************************************************************* */ if ( myid == 0 ) { /* ------------------------------------- Get the max from others and compare ------------------------------------- */ for (i = 1; i < num_procs; i++) { MPI_Irecv(&others_max[i], 1, MPI_DOUBLE,i,0, MPI_COMM_WORLD, &rq_max[i]); } } else { MPI_Send(&my_max, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); } if ( myid == 0 ) { cout << "Done... Now collecting output from others" << endl; for ( i = 1; i < num_procs; i++) { MPI_Wait( &rq_min[i], NULL ); cout << "Min received from proc " << i << " = "<