forked from xharaken/step2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix_simple.c
More file actions
executable file
·65 lines (56 loc) · 1.48 KB
/
matrix_simple.c
File metadata and controls
executable file
·65 lines (56 loc) · 1.48 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
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
double get_time()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec * 1e-6;
}
int main(int argc, char** argv)
{
if (argc != 2) {
printf("usage: %s N\n", argv[0]);
return -1;
}
int n = atoi(argv[1]);
double* a = (double*)malloc(n * n * sizeof(double)); // Matrix A
double* b = (double*)malloc(n * n * sizeof(double)); // Matrix B
double* c = (double*)malloc(n * n * sizeof(double)); // Matrix C
// Initialize the matrices to some values.
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
a[i * n + j] = i * n + j; // A[i][j]
b[i * n + j] = j * n + i; // B[i][j]
c[i * n + j] = 0; // C[i][j]
}
}
double begin = get_time();
// Write code to calculate C = A * B.
int k;
for (i = 0; i < n; i++) {
for (k = 0; k < n; k++) {
for (j = 0; j < n; j++) {
c[i * n + j] += a[i * n + k] * b[k * n + j];
}
}
}
double end = get_time();
printf("time: %.6lf sec\n", end - begin);
// Print C for debugging. Comment out the print before measuring the execution time.
double sum = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
sum += c[i * n + j];
// printf("c[%d][%d]=%lf\n", i, j, c[i * n + j]);
}
}
// Print out the sum of all values in C.
// This should be 450 for N=3, 3680 for N=4, and 18250 for N=5.
printf("sum: %.6lf\n", sum);
free(a);
free(b);
free(c);
return 0;
}