Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://github.com/elahehrashedi/MPI_Matrix_Multiplication_Scatter_Gather/blob/master/matrix.c
- #include <mpi.h>
- #include <stdio.h>
- #include <stdlib.h>
- int main(int argc, char *argv[])
- {
- int matrixSize, rank, size;
- double *sendA, *sendB, *finalC, *recA, *recC;
- MPI::Init(argc, argv);
- size = MPI::COMM_WORLD.Get_size();
- rank = MPI::COMM_WORLD.Get_rank();
- if (rank == 0)
- {
- matrixSize = 10;
- printf("rows is %d \n", matrixSize);
- sendA = new double[matrixSize * matrixSize];
- sendB = new double[matrixSize * matrixSize];
- finalC = new double[matrixSize * matrixSize];
- for (int i = 0; i < matrixSize; i++)
- for (int j = 0; j < matrixSize; j++)
- {
- sendA[i * matrixSize + j] = i + 1;
- }
- for (int i = 0; i < matrixSize; i++)
- for (int j = 0; j < matrixSize; j++)
- {
- sendB[i * matrixSize + j] = j + 1;
- }
- }
- MPI::COMM_WORLD.Barrier();
- MPI::COMM_WORLD.Bcast(&matrixSize, 1, MPI::INT, 0);
- recA = new double[matrixSize / size * matrixSize];
- if (sendB == NULL)
- {
- sendB = new double[matrixSize * matrixSize];
- }
- recC = new double[matrixSize / size * matrixSize];
- // now p0 scatter matrix sendA to all
- MPI::COMM_WORLD.Scatter(sendA, matrixSize * matrixSize / size, MPI::DOUBLE, recA, matrixSize * matrixSize / size, MPI::DOUBLE, 0);
- //now p0 broadcast sendB to all others
- MPI::COMM_WORLD.Bcast(sendB, matrixSize * matrixSize, MPI::DOUBLE, 0);
- // all do this part to calculate recC as multiplicated matrix
- for (int i = 0; i < (matrixSize / size); i++)
- for (int j = 0; j < matrixSize; j++)
- {
- recC[i * matrixSize + j] = 0;
- for (int k = 0; k < matrixSize; k++)
- recC[i * matrixSize + j] += recA[i * matrixSize + k] * sendB[k * matrixSize + j];
- }
- MPI::COMM_WORLD.Barrier();
- MPI::COMM_WORLD.Gather(recC, matrixSize * matrixSize / size, MPI::DOUBLE, finalC, matrixSize * matrixSize / size, MPI::DOUBLE, 0);
- MPI::COMM_WORLD.Barrier();
- if (rank == 0)
- {
- for (int i = 0; i < matrixSize; i++)
- {
- for (int j = 0; j < matrixSize; j++)
- printf(" %.2f ", finalC[i * matrixSize + j]);
- printf("\n");
- }
- }
- MPI::Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement