chundoong-lab-ta/SHPC2022/hw2_answer/vectordot/util.c

79 lines
1.6 KiB
C
Raw Normal View History

2022-10-04 13:56:31 +09:00
#include "util.h"
2022-10-04 21:07:02 +09:00
#include <math.h>
#include <stdbool.h>
2022-10-04 13:56:31 +09:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static double start_time[8];
2022-10-04 21:07:02 +09:00
void timer_init() { srand(time(NULL)); }
2022-10-04 13:56:31 +09:00
static double get_time() {
2022-10-04 21:07:02 +09:00
struct timespec tv;
clock_gettime(CLOCK_MONOTONIC, &tv);
return tv.tv_sec + tv.tv_nsec * 1e-9;
2022-10-04 13:56:31 +09:00
}
2022-10-04 21:07:02 +09:00
void timer_start(int i) { start_time[i] = get_time(); }
2022-10-04 13:56:31 +09:00
2022-10-04 21:07:02 +09:00
double timer_stop(int i) { return get_time() - start_time[i]; }
2022-10-04 13:56:31 +09:00
void alloc_array(float **m, int N) {
2022-10-04 21:07:02 +09:00
*m = (float *)aligned_alloc(32, sizeof(float) * N);
if (*m == NULL) {
printf("Failed to allocate memory for array.\n");
exit(0);
}
2022-10-04 13:56:31 +09:00
}
void rand_array(float *m, int N) {
2022-10-04 21:07:02 +09:00
for (int j = 0; j < N; j++) {
m[j] = (float)rand() / RAND_MAX - 0.5;
}
2022-10-04 13:56:31 +09:00
}
2022-10-04 21:07:02 +09:00
void zero_array(float *m, int N) { memset(m, 0, sizeof(float) * N); }
2022-10-04 13:56:31 +09:00
void print_vec(float *m, int N) {
2022-10-04 21:07:02 +09:00
for (int i = 0; i < N; ++i) {
printf("%+.3f ", m[i]);
}
printf("\n");
2022-10-04 13:56:31 +09:00
}
void print_mat(float *m, int M, int N) {
2022-10-04 21:07:02 +09:00
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
printf("%+.3f ", m[i * N + j]);
2022-10-04 13:56:31 +09:00
}
2022-10-04 21:07:02 +09:00
printf("\n");
}
2022-10-04 13:56:31 +09:00
}
void check_vectordot(float *A, float *B, float candidate, int N) {
2022-10-04 21:07:02 +09:00
printf("Validating...\n");
float answer = 0.f;
for (int i = 0; i < N; ++i) {
answer += A[i] * B[i];
}
bool is_valid = true;
float eps = 1e-3;
if (fabsf(candidate - answer) > eps &&
(answer == 0 || fabsf((candidate - answer) / answer) > eps)) {
printf("correct_value = %f, your_value = %f\n", answer, candidate);
is_valid = false;
}
if (is_valid) {
printf("Result: VALID\n");
} else {
printf("Result: INVALID\n");
}
2022-10-04 13:56:31 +09:00
}