-
Notifications
You must be signed in to change notification settings - Fork 32
/
matrix.c
90 lines (76 loc) · 1.8 KB
/
matrix.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
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <sched.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/resource.h>
/* change dimension size as needed */
struct timeval tv;
int dimension = 1024;
double start, end; /* time */
double timestamp()
{
double t;
gettimeofday(&tv, NULL);
t = tv.tv_sec + (tv.tv_usec/1000000.0);
return t;
}
// a naive matrix multiplication implementation.
void matmult(double *A, double *B, double *C, int dimension)
{
for(int i = 0; i < dimension; i++) {
for(int j = 0; j < dimension; j++) {
for(int k = 0; k < dimension; k++) {
C[dimension*i+j] += A[dimension*i+k] * B[dimension*k+j];
}
}
}
}
int main(int argc, char *argv[])
{
double *A, *B, *C;
unsigned finish = 0;
int i, j, k;
int opt;
int cpuid = 0;
int prio = 0;
int num_processors;
struct sched_param param;
/*
* get command line options
*/
while ((opt = getopt(argc, argv, "m:a:n:t:c:i:p:o:f:l:xh")) != -1) {
switch (opt) {
case 'n':
dimension = strtol(optarg, NULL, 0);
break;
}
}
printf("dimension: %d\n", dimension);
A = (double*)malloc(dimension*dimension*sizeof(double));
B = (double*)malloc(dimension*dimension*sizeof(double));
C = (double*)malloc(dimension*dimension*sizeof(double));
srand(292);
// matrix initialization
for(i = 0; i < dimension; i++) {
for(j = 0; j < dimension; j++)
{
A[dimension*i+j] = (rand()/(RAND_MAX + 1.0));
B[dimension*i+j] = (rand()/(RAND_MAX + 1.0));
C[dimension*i+j] = 0.0;
}
}
// do matrix multiplication
start = timestamp();
matmult(A, B, C, dimension);
end = timestamp();
printf("secs:%f\n", end-start);
free(A);
free(B);
free(C);
return 0;
}