wiki:mpich/collective_communication/demo1

Source code

/* Program:
 *   每個 node 將自己運算後的結果傳回給 root node,而
 *   root node 將結果印出
 * History:
 *   2008-06-10 BETA
 */

#include <stdio.h>
#include <mpi.h>
main (int argc, char **argv)
{
  int rank, size, i;
  int myid, numprocs;
  int myTotal = 0;
  int Total = 0;
  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  MPI_Comm_rank(MPI_COMM_WORLD, &myid);

  for(i = 1; i <= 100; i++)
  {
    if((i % numprocs) == myid)
    {
      myTotal += i;
    }
    MPI_Reduce(&myTotal, &Total, 1, MPI_INT, MPI_SUM, 0,MPI_COMM_WORLD);
  }
  if(myid==0)
  {
    printf("Total = %d\n", Total);
  }
  MPI_Finalize();
}

Result

Last modified 17 years ago Last modified on Jun 18, 2008, 5:52:32 PM

Attachments (1)

Download all attachments as: .zip