cs205-lecture-examples

Example codes used during Harvard CS205 lectures
git clone https://git.0xfab.ch/cs205-lecture-examples.git
Log | Files | Refs | README | LICENSE

mpi_minloc.cpp (708B)


      1 #include <cstdlib>
      2 #include <iostream>
      3 #include <mpi.h>
      4 
      5 int main(int argc, char* argv[])
      6 {
      7     int rank;
      8     MPI_Init(&argc, &argv);
      9     MPI_Comm_rank(MPI_COMM_WORLD, &rank);
     10 
     11     srand48(rank);
     12     const double value = drand48();
     13     std::cout << "Rank " << rank << ": value = " << value << '\n';
     14 
     15     // packed value and rank ID
     16     struct DoubleInt {
     17         double val;
     18         int rank;
     19     } send, recv;
     20     send.val = value;
     21     send.rank = rank;
     22 
     23     MPI_Reduce(&send, &recv, 1, MPI_DOUBLE_INT, MPI_MINLOC, 0, MPI_COMM_WORLD);
     24     if (0 == rank) {
     25         std::cout << "Minimum: value = " << recv.val << " on rank " << recv.rank
     26                   << '\n';
     27     }
     28 
     29     MPI_Finalize();
     30     return 0;
     31 }