chundoong-lab-ta/SamsungDS22/submissions/HW2/hello.kwak/mat_mul.cpp

87 lines
2.0 KiB
C++
Raw Normal View History

2022-09-29 18:01:45 +09:00
#include "mat_mul.h"
#include <immintrin.h>
#include <cstdlib>
#include <cstdio>
#include<algorithm>
#include <pthread.h>
using namespace std;
static float *A, *B, *C;
static int M, N, K;
static int num_threads;
#define BLOCKSIZE 64
static void* mat_mul_thread(void *data) {
// TODO: parallelize & optimize matrix multiplication
// cache blocking + loop unrolling
#if 1
int pid = * (int *) data;
int slice = M / num_threads;
int start = pid * slice;
int end = pid == num_threads - 1 ? M : (pid + 1) * slice;
float A_buf;
int block_s = BLOCKSIZE;
for (int kk = 0; kk < K; kk += block_s) {
for (int i = start; i < end; ++i) {
for (int k = kk; k < min(kk + block_s, K); ++k) {
A_buf = A[i * K + k];
// loop unrolling
int N_8 = (N >> 3) <<3;
int j = 0;
for (; j < N_8; j += 8) {
C[i * N + j] += A_buf * B[k * N + j];
C[i * N + j + 1] += A_buf * B[k * N + j + 1];
C[i * N + j + 2] += A_buf * B[k * N + j + 2];
C[i * N + j + 3] += A_buf * B[k * N + j + 3];
C[i * N + j + 4] += A_buf * B[k * N + j + 4];
C[i * N + j + 5] += A_buf * B[k * N + j + 5];
C[i * N + j + 6] += A_buf * B[k * N + j + 6];
C[i * N + j + 7] += A_buf * B[k * N + j + 7];
}
// unrolling remainder
for (; j < N; ++j) {
C[i * N + j] += A_buf * B[k * N + j];
}
}
}
}
#endif
return NULL;
}
void mat_mul(float *_A, float *_B, float *_C, int _M, int _N, int _K, int _num_threads) {
A = _A, B = _B, C = _C;
M = _M, N = _N, K = _K;
num_threads = _num_threads;
// TODO: create '_num_threads' pthreads
pthread_t * thread;
thread = (pthread_t *) malloc(sizeof(pthread_t) * num_threads);
for (int i = 0; i < num_threads; i++) {
int * pid = (int *) malloc(sizeof(int));
*pid = i;
pthread_create(&thread[i], NULL, mat_mul_thread, pid);
}
for (int i = 0; i < num_threads; i++) {
pthread_join(thread[i], NULL);
}
}