Skip to content

Instantly share code, notes, and snippets.

@lazarljubenovic
Created June 17, 2017 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazarljubenovic/7c65ea2a08d8df8b217d506f58a98f6d to your computer and use it in GitHub Desktop.
Save lazarljubenovic/7c65ea2a08d8df8b217d506f58a98f6d to your computer and use it in GitHub Desktop.
#include <mpi.h>
#include <stdio.h>
#define W MPI_COMM_WORLD
void printArray(int n, int array[n], int rank) {
for (int i = 0; i < n; i++) {
if (rank == -1) printf("%4d ", array[i]);
else printf("{%d}%4d ", rank, array[i]);
}
printf("\n");
}
void printMatrix(int n, int m, int matrix[n][m], int rank) {
for (int i = 0; i < n; i++) {
printArray(m, matrix[i], rank);
}
}
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(W, &rank);
MPI_Comm_size(W, &size);
int n = 6;
int k = 2;
int A[n][n], B[n][n], C[n][n],
locA[n][k], locB[k][n], locC[n][n];
// Inicijalizacija matrica A i B
if (rank == 0) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = i * 10 + j;
B[i][j] = i * 10 + j;
}
}
}
// Definicija tipa za slanje kolona
MPI_Datatype MPI_COL;
MPI_Type_vector(n, k, n, MPI_INT, &MPI_COL);
MPI_Type_create_resized(MPI_COL, 0, k * sizeof(int), &MPI_COL);
MPI_Type_commit(&MPI_COL);
// Rasporedjuju se kolone matrice A i vrste matrice B
MPI_Scatter(A, 1, MPI_COL, locA, n*k, MPI_INT, 0, W);
MPI_Scatter(B, n*k, MPI_INT, locB, n*k, MPI_INT, 0, W);
// Svaki proces lokalno cuva deo koji moze da izracuna.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
locC[i][j] = 0;
for (int q = 0; q < k; q++) {
locC[i][j] += locA[i][q] * locB[q][j];
}
}
}
// Sabiramo sve parcijalne matrice, saljemo masteru.
MPI_Reduce(locC, C, n * n, MPI_INT, MPI_SUM, 0, W);
// Master prikazuje matricu.
if (rank == 0) {
printMatrix(n, n, C, -1);
}
MPI_Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment