-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmpi_multi_matrice.cpp
More file actions
93 lines (72 loc) · 2.22 KB
/
Copy pathmpi_multi_matrice.cpp
File metadata and controls
93 lines (72 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <cstdlib>
#include <ctime>
#include <random>
#include <mpi.h>
const int limit = 10;
int main(int argc, char* argv[]) {
int n = strtol(argv[1], NULL, 10);
// int num_thrs = strtol(argv[2], NULL, 10);
int i, j, k;
int local_rows;
int* A = NULL;
int* B = new int[n * n];
int* C = NULL;
int rank, size;
MPI_Init(NULL, NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
int rem = n % size;
local_rows = (rank < rem) ? n / size + 1 : n / size;
int* local_A = new int[local_rows * n];
int* local_C = new int[local_rows * n]();
if (rank == 0) {
A = new int[n * n];
C = new int[n * n]();
srand(static_cast<unsigned>(time(0)));
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
A[i * n + j] = rand() % limit;
B[i * n + j] = rand() % limit;
}
}
}
int* sendcounts = nullptr;
int* displs = nullptr;
if (rank == 0) {
sendcounts = new int[size];
displs = new int[size];
int disp = 0;
for (int r = 0; r < size; r++) {
sendcounts[r] = ((r < rem) ? n / size + 1 : n / size) * n;
displs[r] = disp;
disp += sendcounts[r];
}
}
MPI_Scatterv(A, sendcounts, displs, MPI_INT, local_A, local_rows * n, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(B, n * n, MPI_INT, 0, MPI_COMM_WORLD);
double start, end;
start = MPI_Wtime();
for (i = 0; i < local_rows; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
local_C[i * n + j] += local_A[i * n + k] * B[k * n + j];
}
}
}
end = MPI_Wtime();
MPI_Gatherv(local_C, local_rows * n, MPI_INT, C, sendcounts, displs, MPI_INT, 0, MPI_COMM_WORLD);
double duration = end - start;
if (rank == 0) {
printf("cost time: \t%lfs\n", duration);
delete[] A;
delete[] C;
delete[] sendcounts;
delete[] displs;
}
delete[] local_A;
delete[] local_C;
delete[] B;
MPI_Finalize();
return 0;
}
// mpiexec ./mpi_multi_matrice <the amount of data> -n <the number of processors>