Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include "mpi.h"
  5.  
  6. #define NUM_MESSAGES 100
  7. #define FROM_MASTER 0
  8.  
  9. #define MASTER(rank) (rank == 0)
  10. #define SLAVE(rank) (!MASTER)
  11.  
  12. //-----------------------------------------------------------------------
  13.  
  14. int main(int argc, char *argv[])
  15. {
  16.   int rank, size;
  17.   double start_time = 0;
  18.   double end_time = 0;
  19.   MPI_Status status;
  20.  
  21.   MPI_Init(&argc,&argv);
  22.  
  23.   MPI_Comm_size(MPI_COMM_WORLD, &size); // p
  24.   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  25.  
  26.   MPI_Barrier(MPI_COMM_WORLD);
  27.  
  28.   // start timing
  29.   if (MASTER(rank)) {
  30.     start_time = MPI_Wtime();
  31.   }
  32.  
  33.   char* msg = "hello!";
  34.  
  35.   MPI_Barrier(MPI_COMM_WORLD);
  36.  
  37.   int index = 0;
  38.   for (index = 0; index < NUM_MESSAGES; index++) {
  39.     if (MASTER(rank)) {
  40.       //printf("master is sending message to node 1\n");
  41.       MPI_Send(&msg, 6, MPI_CHAR, 1, FROM_MASTER, MPI_COMM_WORLD);
  42.  
  43.       //printf("master is waiting for message from node %d\n", size - 1);
  44.       MPI_Recv(&msg, 6, MPI_CHAR, size - 1, FROM_MASTER, MPI_COMM_WORLD, &status);
  45.     } else {
  46.       MPI_Recv(&msg, 6, MPI_CHAR, rank-1, FROM_MASTER, MPI_COMM_WORLD, &status);
  47.  
  48.       if (rank + 1 == size) {
  49.         //printf("node %d is sending a message to node 0\n", rank);
  50.         MPI_Send(&msg, 6, MPI_CHAR, 0, FROM_MASTER, MPI_COMM_WORLD);
  51.       } else {
  52.         //printf("node %d is sending a message to node %d\n", rank, rank + 1);
  53.         MPI_Send(&msg, 6, MPI_CHAR, rank + 1, FROM_MASTER, MPI_COMM_WORLD);
  54.       }
  55.     }
  56.  
  57.     MPI_Barrier(MPI_COMM_WORLD);
  58.   }
  59.  
  60.   MPI_Barrier(MPI_COMM_WORLD);
  61.   if (MASTER(rank)) {
  62.     end_time = MPI_Wtime();
  63.   }
  64.   // end timing
  65.  
  66.   if (MASTER(rank)) {
  67.     printf("All done sending %d messages between %d nodes!\n", NUM_MESSAGES, size);
  68.     printf("It took %f seconds\n", end_time-start_time);
  69.   }
  70.  
  71.   //printf("calling MPI_Finalize()\n");
  72.   MPI_Finalize();
  73.   return(0);
  74. }
  75.  
  76. //-----------------------------------------------------------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement