cs.cc 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include <mpi.h>
  2. #include <cassert>
  3. #include <cmath>
  4. #include <iostream>
  5. #include <random>
  6. #define SERVER_NUM 2
  7. #define LOOP 1024
  8. std::random_device rd;
  9. std::mt19937 gen(rd());
  10. std::uniform_real_distribution<> dis(0, 2047);
  11. int main(int argc, char *argv[]) {
  12. int rank, size;
  13. // MPI init
  14. MPI_Init(&argc, &argv);
  15. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  16. MPI_Comm_size(MPI_COMM_WORLD, &size);
  17. // server or client
  18. int SorC = rank >= SERVER_NUM;
  19. MPI_Comm serverClient, service;
  20. MPI_Comm_split(MPI_COMM_WORLD, SorC, -1, &serverClient);
  21. int service_num = rank % SERVER_NUM;
  22. MPI_Comm_split(MPI_COMM_WORLD, service_num, SorC, &service);
  23. int service_rank;
  24. MPI_Comm_rank(service, &service_rank);
  25. // start
  26. float value;
  27. float sum;
  28. for (int i = 0; i < LOOP; ++i) {
  29. if (SorC) { // client
  30. value = dis(gen);
  31. // printf("c:%d, %d, %f\n", rank, service_rank, value);
  32. } else { // server
  33. value = 0;
  34. }
  35. MPI_Reduce(&value, &sum, 1, MPI_FLOAT, MPI_SUM, 0, service);
  36. if (!SorC) {
  37. // printf("s:%d, %d, %f\n", rank, service_rank, sum);
  38. MPI_Allreduce(&sum, &value, 1, MPI_FLOAT, MPI_SUM, serverClient);
  39. value /= (size - SERVER_NUM);
  40. // printf("s:%d, %d, %f\n", rank, service_rank, value);
  41. }
  42. MPI_Bcast(&value, 1, MPI_FLOAT, 0, service);
  43. // printf("c:%d, %f\n", rank, value);
  44. }
  45. MPI_Finalize();
  46. }