Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <mpi.h>
- using namespace std;
- int main(int argc, char* argv[]) {
- srand(time(NULL));
- MPI_Init(&argc, &argv);
- int world_size;
- int world_rank;
- MPI_Comm_size(MPI_COMM_WORLD, &world_size);
- MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
- int* arr = nullptr;
- int* arrSums = nullptr;
- int n;
- if (world_rank == 0) {
- cin >> n;
- arr = new int[n];
- arrSums = new int[world_size];
- cout << "Сгенерированный массив: ";
- for (int i = 0; i < n; i++) {
- arr[i] = rand() % 10;
- cout << arr[i] << " ";
- }
- cout << endl;
- }
- MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
- const int BUF_SIZE = n / world_size;
- int* arrLocal = new int[BUF_SIZE];
- MPI_Scatter(arr, BUF_SIZE, MPI_INT, arrLocal, BUF_SIZE, MPI_INT, 0, MPI_COMM_WORLD);
- int sum = 0;
- for (int i = 0; i < BUF_SIZE; ++i) {
- sum += arrLocal[i];
- }
- cout << "Процессор: " << world_rank << ", сумма: " << sum << endl;
- MPI_Gather(&sum, 1, MPI_INT, arrSums, 1, MPI_INT, 0, MPI_COMM_WORLD);
- int totalSum = 0;
- if (world_rank == 0) {
- for (int i = 0; i < world_size; ++i) {
- totalSum += arrSums[i];
- }
- cout << "Общая сумма: " << totalSum << endl;
- }
- MPI_Finalize();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement