reduce.c

#include<stdio.h>
#include<mpi.h>
#define MAX 10000
/***************************************************
mpicc -o reduce reduce.c
mpirun -np 10 reduce
int    MPI_Reduce(
  void     *sendBuf;
  void     *receiveBuf;
  int             count;
  MPI_Datatype    dataType;    //e.g., MPI_INT
  MPI_Op    operator;     //e.g., MPI_SUM
  int    root;         // root process
  MPI_Comm  comm
)
***************************************************/

int getValue( int rank, int value){
   return value;
}

int main( int argc, char *argv[]){
   int numTasks, rank, rc;
    
  rc = MPI_Init(&argc, &argv);
   if(rc != MPI_SUCCESS) {
    printf( "Error Starting MPI program. Terminating.\n");
    MPI_Abort(MPI_COMM_WORLD, rc);     //errorCode
  }
    
  MPI_Barrier(MPI_COMM_WORLD);
   double wallTime1 = MPI_Wtime(); //
   double precision = MPI_Wtick(); //wallTime's precision

  MPI_Comm_size(MPI_COMM_WORLD, &numTasks); //get from -np    
  MPI_Comm_rank(MPI_COMM_WORLD, &rank); //each process's ID
                
         int i, globalSolutions, localSolutions = 0;
   for(i = rank; i < MAX; i += numTasks){           //interleave data distribution
    localSolutions += getValue(rank, i);
  }
    
  MPI_Reduce(&localSolutions, &globalSolutions, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);        
    
  printf( "Process %d is done.\n", rank);
  fflush(stdout);
    
   double wallTime2 = MPI_Wtime();
    
   if(rank == 0){     // if(!rank)
    printf( "argc = %d\n", argc);
     int i;
     for(i = 0; i < argc; i++)
      printf( "argv[%d] = %s\n", i, argv[i]);

    printf( "elapsedTime = %f, precision = %f\n", wallTime2 - wallTime1, precision);
                printf( "globalSolutions = %d\n", globalSolutions);
  }
    
  MPI_Finalize();
   return 0;
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息