#include "mpi.h" #include #include #define MAXSIZE 1000 int main(int argc, char *argv) { int myid, numprocs; int data[MAXSIZE], i, n, x, low, high, myresult, result; double start, stop; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&numprocs); MPI_Comm_rank(MPI_COMM_WORLD,&myid); n = MAXSIZE; if (myid == 0) { /* initialize data */ for(i = 0; i < n; i++) { data[i] = 1; } } if (myid == 0 ) start = MPI_Wtime(); /* broadcast data */ MPI_Bcast(data, n, MPI_INT, 0, MPI_COMM_WORLD); /* Add my portion of data */ x = n/numprocs; low = myid * x; high = low + x; for(i = low; i < high; i++) { compute(); /* do some computation */ myresult += data[i]; } printf("I got %d from %d\n", myresult, myid); /* Compute global sum */ MPI_Reduce(&myresult, &result, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (myid == 0) printf("The sum is %d.\n", result); if (myid == 0) { stop = MPI_Wtime(); printf("parallel section time %f", stop-start); } MPI_Finalize(); } compute() { int i; for (i=0; i<1000000; i++); }