Posted 2010/09/03
MPI find minimum demo
How to find the 'find minimum' using MPI.
#include "mpi.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #define MAXSIZE 1000 void main(int argc, char **argv) { int myid, numprocs, data[MAXSIZE], i, x, myresult, result, status; FILE *fp; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&numprocs); MPI_Comm_rank(MPI_COMM_WORLD,&myid); if(myid == 0){ if((fp = fopen("./rand_data.txt", "r")) == NULL){ printf("Can't open the input file\n"); exit(0); } for(i = 0; i < MAXSIZE; i++) status=fscanf(fp,"%d", &data[i]); } MPI_Bcast(data, MAXSIZE, MPI_INT, 0, MPI_COMM_WORLD); /* broadcast data */ myresult=data[myid]; printf("Rank %d had: %d\n", myid, myresult); MPI_Reduce(&myresult, &result, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD); if(myid == 0){ printf("The minimum is %d.\n", result); } MPI_Finalize(); }
Fill ./rand_data.txt with 1000 random integers.