forked from dimitrisstyl7/parallel-computing-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmm_omp.c
121 lines (103 loc) · 2.79 KB
/
mm_omp.c
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
double *A, *B, *C;
long N, K, M;
int main(int argc, char *argv[])
{
long printResults;
char *EndPtr;
struct timeval start, end;
double elapsed_time;
if (argc != 5)
{
printf("USAGE: %s <N> <K> <M> <PRINT RESULTS> \n", argv[0]);
exit(1);
}
N = strtol(argv[1], &EndPtr, 10);
if (*EndPtr != '\0' || N < 1)
{
printf("Invalid number for N provided.\n");
exit(1);
}
K = strtol(argv[2], &EndPtr, 10);
if (*EndPtr != '\0' || K < 1)
{
printf("Invalid number for K provided.\n");
exit(1);
}
M = strtol(argv[3], &EndPtr, 10);
if (*EndPtr != '\0' || M < 1)
{
printf("Invalid number for M provided.\n");
exit(1);
}
printResults = strtol(argv[4], &EndPtr, 10);
if (*EndPtr != '\0')
{
printf("Invalid number for printResults provided.\n");
exit(1);
}
/*
* Allocate memory for input and output arrays.
* All elementrs of the output array are initialized to 0.
*/
A = (double *)malloc(N * K * sizeof(double));
if (A == NULL)
{
printf("Could not allocate memory for array A.\n");
exit(2);
}
B = (double *)malloc(K * M * sizeof(double));
if (B == NULL)
{
printf("Could not allocate memory for array B.\n");
free(A);
exit(2);
}
C = (double *)calloc(N * M, sizeof(double));
if (C == NULL)
{
printf("Could not allocate memory for array C.\n");
free(A);
free(B);
exit(2);
}
printf("Starting initialization of array A.\n");
for (int i = 0; i < N; i++)
for (int j = 0; j < K; j++)
A[i * K + j] = 3.0 * drand48();
printf("Finished initialization of array A.\n");
printf("Starting initialization of array B.\n");
for (int i = 0; i < K; i++)
for (int j = 0; j < M; j++)
B[i * M + j] = 3.0 * drand48();
printf("Finished initialization of array B.\n");
/*
* Matrix-Matrix multiplication
*/
gettimeofday(&start, NULL);
#pragma omp parallel
{
#pragma omp for
for (int i = 0; i < N; i++)
for (int k = 0; k < K; k++)
for (int j = 0; j < M; j++)
C[i * M + j] += A[i * K + k] * B[k * M + j];
}
gettimeofday(&end, NULL);
elapsed_time = (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.0;
printf("Time for multiplication: %f sec\n", elapsed_time);
if (printResults != 0)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
printf("%25.16f", C[i * M + j]);
}
printf("\n");
}
}
return (0);
}