chundoong-lab-ta/SamsungDS22/submissions/HW2/jaehyun5.kim/mat_mul.cpp

70 lines
1.8 KiB
C++
Raw Normal View History

2022-09-29 18:01:45 +09:00
#include "mat_mul.h"
#include <cstdlib>
#include <cstdio>
#include <pthread.h>
static float *A, *B, *C;
static int M, N, K;
static int num_threads;
int min(int a,int b)
{
return (a<b)?a:b;
}
static void* mat_mul_thread(void *data) {
// TODO: parallelize & optimize matrix multiplication
int index = * (int *) data;
int offset = M / num_threads;
int start = index * offset;
int end = (index == num_threads - 1) ? M : (index + 1) * offset;
int kk, i, k, j;
float A_calc;
int bs = 32;
for (kk = 0; kk < K; kk += bs) {
for (i = start; i < end; ++i) {
for (k = kk; k < min(kk + bs, K); k++) {
A_calc = A[i * K + k];
if(!(N%8)){
for (j = 0; j < N; j=j+4) {
C[i * N + j] += A_calc * B[k * N + j];
C[i * N + j+1] += A_calc * B[k * N + j+1];
C[i * N + j+2] += A_calc * B[k * N + j+2];
C[i * N + j+3] += A_calc * B[k * N + j+3];
//C[i * N + j+4] += A_calc * B[k * N + j+4];
//C[i * N + j+5] += A_calc * B[k * N + j+5];
//C[i * N + j+6] += A_calc * B[k * N + j+6];
//C[i * N + j+7] += A_calc * B[k * N + j+7];
}
}
else{
for(j=0;j<N;j++){
C[i * N + j] += A_calc * B[k * N + j];
}
}
}
}
}
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[num_threads];
for(int i=0;i<num_threads;i++){
int* index = (int*)malloc(sizeof(int));
*index=i;
pthread_create(&thread[i], NULL, mat_mul_thread, index);
}
for(int i=0;i<num_threads;i++)
pthread_join(thread[i], NULL);
}