![](http://static.javashuo.com/static/loading.gif)
#include<stdio.h>
![](http://static.javashuo.com/static/loading.gif)
#include<mpi.h>
![](http://static.javashuo.com/static/loading.gif)
#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;
![](http://static.javashuo.com/static/loading.gif)
}
int main(
int argc,
char *argv[]){
int numTasks, rank, rc;
![](http://static.javashuo.com/static/loading.gif)
rc = MPI_Init(&argc, &argv);
if(rc != MPI_SUCCESS) {
![](http://static.javashuo.com/static/loading.gif)
printf(
"Error Starting MPI program. Terminating.\n");
![](http://static.javashuo.com/static/loading.gif)
MPI_Abort(MPI_COMM_WORLD, rc);
//errorCode
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
MPI_Barrier(MPI_COMM_WORLD);
double wallTime1 = MPI_Wtime();
//
double precision = MPI_Wtick();
//wallTime's precision
![](http://static.javashuo.com/static/loading.gif)
MPI_Comm_size(MPI_COMM_WORLD, &numTasks);
//get from -np
![](http://static.javashuo.com/static/loading.gif)
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
![](http://static.javashuo.com/static/loading.gif)
localSolutions += getValue(rank, i);
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
MPI_Reduce(&localSolutions, &globalSolutions, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
![](http://static.javashuo.com/static/loading.gif)
printf(
"Process %d is done.\n", rank);
![](http://static.javashuo.com/static/loading.gif)
fflush(stdout);
double wallTime2 = MPI_Wtime();
if(rank == 0){
// if(!rank)
![](http://static.javashuo.com/static/loading.gif)
printf(
"argc = %d\n", argc);
int i;
for(i = 0; i < argc; i++)
![](http://static.javashuo.com/static/loading.gif)
printf(
"argv[%d] = %s\n", i, argv[i]);
![](http://static.javashuo.com/static/loading.gif)
printf(
"elapsedTime = %f, precision = %f\n", wallTime2 - wallTime1, precision);
![](http://static.javashuo.com/static/loading.gif)
printf(
"globalSolutions = %d\n", globalSolutions);
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
MPI_Finalize();
return 0;
![](http://static.javashuo.com/static/loading.gif)
}