Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include "mpi.h"
- #include <iostream>
- using namespace std;
- int main(int* argc, char** argv)
- {
- int vecResult [10];
- int vec[10];
- int matrix[10][10];
- MPI_Init(argc, &argv);
- int world_rank, world_size;;
- MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
- MPI_Comm_size(MPI_COMM_WORLD, &world_size);
- for (auto i = 0; i < 10; i++) vecResult[i] = 0;
- const int arrayCount = sizeof matrix / sizeof matrix[0];
- const int sizeBlock = sizeof matrix[0] / sizeof matrix[0][0];
- int* len = static_cast<int*>(malloc(sizeof(int) * world_size));
- int* index = static_cast<int*>(malloc(sizeof(int) * world_size));
- int* vecLen = static_cast<int*>(malloc(sizeof(int) * world_size));
- int* vecIndex = static_cast<int*>(malloc(sizeof(int) * world_size));
- if (arrayCount % world_size == 0)
- {
- const auto l = arrayCount * sizeBlock / world_size;
- for (auto i = 0; i < world_size; i++)
- {
- len[i] = l;
- index[i] = (i)*l;
- vecLen[i] = arrayCount / world_size;
- vecIndex[i] = i * (arrayCount / world_size);
- }
- }
- else
- {
- auto k = 0;
- auto c = arrayCount / world_size;
- for (auto i = 0; i < arrayCount % world_size; ++i)
- {
- len[i] = sizeBlock * (c + 1);
- index[i] = k;
- vecLen[i] = c + 1;
- vecIndex[i] = i * (c + 1);
- k += len[i];
- }
- for (auto i = arrayCount % world_size; i < world_size; i++)
- {
- len[i] = sizeBlock * (c);
- index[i] = k;
- k += len[i];
- vecLen[i] = c;
- vecIndex[i] = i * (c);
- }
- }
- if (world_rank == 0)
- {
- for (int i = 0; i < arrayCount; ++i)
- {
- for (int j = 0; j < sizeBlock; ++j)
- {
- matrix[i][j] = rand() % 10;
- }
- vec[i] = rand() % 10;
- }
- }
- const auto countOfRow = (len[world_rank]) / sizeBlock;
- auto* const localMatrix = static_cast<int*>(malloc(sizeof(int) * countOfRow * sizeBlock));
- auto* const localVec = static_cast<int*>(malloc(sizeof(int) * countOfRow));
- MPI_Scatterv(matrix, len, index, MPI_INT, localMatrix, len[world_rank], MPI_INT, 0, MPI_COMM_WORLD);
- MPI_Scatterv(vec, vecLen, vecIndex, MPI_INT, localVec, len[world_rank], MPI_INT, 0, MPI_COMM_WORLD);
- int* localSum = static_cast<int*>(malloc(sizeof(int) * countOfRow));
- for (int i = 0; i < countOfRow; ++i)
- {
- localSum[i] = 0;
- for (int j = 0; j < sizeBlock; ++j)
- localSum[i] += *(localMatrix + i * sizeBlock + j) * *(localVec + j);
- }
- const auto localIndex = vecIndex[world_rank];
- auto* localArray = static_cast<int*>(malloc(sizeof(int) * sizeBlock));
- for (int i = 0; i < sizeBlock; ++i) localArray[i] = 0;
- for (int i = 0; i < countOfRow; ++i) localArray[localIndex + i] = localSum[i];
- MPI_Reduce(localArray, vecResult, sizeBlock, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
- //Вывод и конец
- if (world_rank == 0)
- for (int i = 0; i < arrayCount; ++i)
- printf("%d \n", vecResult[i]);
- MPI_Finalize();
- }
Advertisement
Add Comment
Please, Sign In to add comment