-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTransposeMatrix.c
More file actions
96 lines (80 loc) · 2.24 KB
/
TransposeMatrix.c
File metadata and controls
96 lines (80 loc) · 2.24 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
94
95
96
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
int** MemoryAllocate(int n) {
int** matrix = (int**)malloc(n * sizeof(int*));
for (int i = 0; i < n; ++i) {
matrix[i] = (int*)malloc(n * sizeof(int));
}
return matrix;
}
void PrintMatrix(int** matrix, int n) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main(int argc, char** argv) {
int num_procs;
int rank;
int n = strtol(argv[1], NULL, 10);
int** matrix = MemoryAllocate(n);
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
unsigned int seed;
if (rank == 0) {
seed = time(NULL);
for (int i = 1; i < num_procs; ++i){
MPI_Send(&seed, 1, MPI_UNSIGNED, i, 1, MPI_COMM_WORLD);
}
}
else {
MPI_Recv(&seed, 1, MPI_UNSIGNED, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
srand(seed);
////////
for (int i = 0; i < n; ++i){
for (int j = 0; j < n; ++j){
matrix[i][j] = random() / (RAND_MAX/100);
}
}
if (rank != 0) {
int k = rank-1;
while (k < n) {
for (int j = 0; j < n; ++j){
matrix[k][j] = matrix[j][k];
}
MPI_Send(matrix[k], n, MPI_INT, 0, k, MPI_COMM_WORLD);
//printf("%d: Send with %d tag\n", rank, k);
k += (num_procs - 1);
}
}
if (rank == 0) {
double t1, t2;
t1 = MPI_Wtime();
if (n < 6) {
PrintMatrix(matrix, n);
}
for (int i = 0; i < n; ++i) {
MPI_Recv(matrix[i], n, MPI_INT, MPI_ANY_SOURCE, i, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
//printf("%d: Received with %d tag\n", rank, i);
}
if (n < 6) {
PrintMatrix(matrix, n);
}
t2 = MPI_Wtime();
printf("%f time spend\n", t2 - t1);
}
for (int i = 0; i < n; ++i) {
free(matrix[i]);
}
free(matrix);
MPI_Finalize();
return 0;
}