-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.h
More file actions
113 lines (91 loc) · 2.78 KB
/
utils.h
File metadata and controls
113 lines (91 loc) · 2.78 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <stdio.h>
#include <stdlib.h>
#ifdef DEBUG
#define KERNEL_DEBUG(fmt, ...) \
printf("[Thread %d %d (Block %d %d)] " fmt, \
threadIdx.x, threadIdx.y, blockIdx.x, blockIdx.y, ##__VA_ARGS__);
#else
#define KERNEL_DEBUG(fmt, ...);
#endif
// Divide x/y and round up
#define CEIL_DIVISION(x, y) ((x) + (y) - 1)/(y)
double *read_double_matrix(const char *filename, int *rows, int *cols) {
FILE *file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "Error opening file\n");
exit(-1);
}
if (fscanf(file, "%d %d\n", rows, cols) != 2) {
fprintf(stderr, "Invalid matrix format\n");
fclose(file);
exit(-1);
}
double *matrix = (double *)malloc((*rows) * (*cols) * sizeof(double));
for (int i = 0; i < (*rows) * (*cols); i++) {
if (fscanf(file, "%lf", &matrix[i]) != 1) {
fprintf(stderr, "Invalid matrix data\n");
fclose(file);
exit(-1);
}
}
fclose(file);
return matrix;
}
void write_double_matrix(const char *filename, double *matrix, int rows, int cols) {
FILE *file = fopen(filename, "w");
if (!file) {
fprintf(stderr, "Error opening file\n");
exit(-1);
}
fprintf(file, "%d %d\n", rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
fprintf(file, "%lf ", matrix[i * cols + j]);
}
fprintf(file, "\n");
}
fclose(file);
}
float *read_float_matrix(const char *filename, int *rows, int *cols) {
FILE *file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "Error opening file\n");
exit(-1);
}
if (fscanf(file, "%d %d\n", rows, cols) != 2) {
fprintf(stderr, "Invalid matrix format\n");
fclose(file);
exit(-1);
}
float *matrix = (float *)malloc((*rows) * (*cols) * sizeof(float));
for (int i = 0; i < (*rows) * (*cols); i++) {
if (fscanf(file, "%f", &matrix[i]) != 1) {
fprintf(stderr, "Invalid matrix data\n");
fclose(file);
exit(-1);
}
}
fclose(file);
return matrix;
}
void write_float_matrix(const char *filename, float *matrix, int rows, int cols) {
FILE *file = fopen(filename, "w");
if (!file) {
fprintf(stderr, "Error opening file\n");
exit(-1);
}
fprintf(file, "%d %d\n", rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
fprintf(file, "%f ", matrix[i * cols + j]);
}
fprintf(file, "\n");
}
fclose(file);
}
void validate_dimensions(int rowsA, int colsA, int rowsB, int colsB) {
if (colsA != rowsB) {
fprintf(stderr, "Matrix dimensions mismatch: %d != %d\n", colsA, rowsB);
exit(-1);
}
}