This repository has been archived by the owner on Dec 21, 2024. It is now read-only.
generated from cmse822/proj1_template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatmul_Cheng.c
78 lines (64 loc) · 2.2 KB
/
matmul_Cheng.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
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <math.h>
// ChatGPT assisted code to run matrix multiplication and analysis
float** generate_matrix(int rows, int cols) {
float** matrix = (float**)malloc(rows * sizeof(float*));
for (int i = 0; i < rows; i++) {
matrix[i] = (float*)malloc(cols * sizeof(float));
}
// Fill the matrix with random numbers
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = (float)rand() / (float)(RAND_MAX);
}
}
return matrix;
}
float** multiply_matrices(float** A, float** B, int size) {
float** AB = (float**)malloc(size * sizeof(float*));
for (int i = 0; i < size; i++) {
AB[i] = (float*)malloc(size * sizeof(float));
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
AB[i][j] = 0;
for (int l = 0; l < size; l++) {
AB[i][j] += A[i][l] * B[l][j];
}
}
}
return AB;
}
int main() {
srand(time(NULL));
const int size = 5000;
float** A = generate_matrix(size, size);
float** B = generate_matrix(size, size);
// Clock time to measure multiply_matrices time
struct timeval startTime, endTime;
// Compute multiplication of matrices and measure time
gettimeofday(&startTime, NULL);
float** AB = multiply_matrices(A, B, size);
gettimeofday(&endTime, NULL);
// Calculate the amount of time used
double executionTime = (double)(endTime.tv_sec - startTime.tv_sec) +
(double)(endTime.tv_usec - startTime.tv_usec) / 1000000.0;
// Calculate the number of mflops/s for matrix multiplication
double Mflops_total = (2 * pow(size, 3) - pow(size, 2)) / pow(10, 6);
double performance_mflops = Mflops_total / executionTime;
printf("Total number of Mflops: %f \n", Mflops_total);
printf("Execution time: %f seconds \n", executionTime);
printf("Total performance in Mflops/s: %f \n", performance_mflops);
// Free the allocated memory
for (int i = 0; i < size; i++) {
free(A[i]);
free(B[i]);
free(AB[i]);
}
free(A);
free(B);
free(AB);
return 0;
}