Advertisement
Guest User

Untitled

a guest
Dec 13th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <mpi.h>
  4.  
  5. using namespace std;
  6.  
  7. int main(int argc, char* argv[]) {
  8.     srand(time(NULL));
  9.     MPI_Init(&argc, &argv);
  10.     int world_size;
  11.     int world_rank;
  12.     MPI_Comm_size(MPI_COMM_WORLD, &world_size);
  13.     MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
  14.    
  15.     int* arr = nullptr;
  16.     int* arrSums = nullptr;
  17.     int n;
  18.    
  19.     if (world_rank == 0) {
  20.         cin >> n;
  21.  
  22.         arr = new int[n];
  23.         arrSums = new int[world_size];
  24.         cout << "Сгенерированный массив: ";
  25.         for (int i = 0; i < n; i++) {
  26.             arr[i] = rand() % 10;
  27.             cout << arr[i] << " ";
  28.         }
  29.         cout << endl;
  30.     }
  31.     MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
  32.     const int BUF_SIZE = n / world_size;
  33.     int* arrLocal = new int[BUF_SIZE];
  34.    
  35.     MPI_Scatter(arr, BUF_SIZE, MPI_INT, arrLocal, BUF_SIZE, MPI_INT, 0, MPI_COMM_WORLD);
  36.    
  37.     int sum = 0;
  38.     for (int i = 0; i < BUF_SIZE; ++i) {
  39.         sum += arrLocal[i];
  40.     }
  41.     cout << "Процессор: " << world_rank << ", сумма: " << sum << endl;
  42.    
  43.     MPI_Gather(&sum, 1, MPI_INT, arrSums, 1, MPI_INT, 0, MPI_COMM_WORLD);
  44.     int totalSum = 0;
  45.     if (world_rank == 0) {
  46.         for (int i = 0; i < world_size; ++i) {
  47.             totalSum += arrSums[i];
  48.         }
  49.         cout << "Общая сумма: " << totalSum << endl;
  50.     }
  51.     MPI_Finalize();
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement