#include #include #include #include #include "mpi.h" int main(int argc, char *argv[]) { int nlocal,offset; int x,n,max=0,local_max=0; double sum=0,local_sum=0; int numprocs,myrank; int rank_left,rank_right; int tag1=1,tag2=2; int *tmp,*buffer,*nextbuffer; MPI_Status status; MPI_Request request1,request2; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); /* Exit if # of arguments < 2 */ if (argc < 3) { if (myrank==0) printf("Usage: %s \n",argv[0]); MPI_Finalize(); exit(1); } int N=atoi(argv[1]); int Niter=atoi(argv[2]); if (myrank==0) { printf("\nSize of the array: %d\n",N); printf("Number of iterations: %d\n\n",Niter); } /* Calculate the size of local array. */ nlocal=N/numprocs; offset=myrank*nlocal; buffer = (int*)malloc((nlocal+2) * sizeof(int)); nextbuffer = (int*)malloc((nlocal+2) * sizeof(int)); /* Initialize the array. */ for (x=0; xlocal_max) local_max=buffer[x]; } /* Reduce the result to the root process. */ MPI_Reduce(&local_sum,&sum,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD); MPI_Reduce(&local_max,&max,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD); if (myrank==0) { printf("Maximum: %d\n",max); printf("Average: %f\n\n",sum/(double)N); } free(buffer); free(nextbuffer); MPI_Finalize(); }