chundoong-lab-ta/SamsungDS22/submissions/HW2/minseok_5.oh/mat_mul.cpp

85 lines
2.4 KiB
C++

#include "mat_mul.h"
#include <cstdlib>
#include <cstdio>
#include <pthread.h>
#include <algorithm>
#define BLOCK_SIZE 40
static float *A, *B, *C;
static int M, N, K;
static int num_threads;
static void* mat_mul_thread(void *data) {
// TODO: parallelize & optimize matrix multiplication
int pid = * (int *) data;
int S = ( M/num_threads);
int start = ( pid*S );
int end = ( pid == (num_threads-1)) ? M : (pid+1) * S;
float Aik;
for (int kk = 0; kk < K; kk += BLOCK_SIZE) {
for (int i = start; i < end; ++i) {
for (int k = kk; k < std::min(kk + BLOCK_SIZE, K); ++k) {
Aik = A[(i*K) + k];
int j;
for (j = 0; j < N-16; j += 16) {
C[ (i*N) + j + 0 ] += Aik * B[ (k*N) + j + 0 ];
C[ (i*N) + j + 1 ] += Aik * B[ (k*N) + j + 1 ];
C[ (i*N) + j + 2 ] += Aik * B[ (k*N) + j + 2 ];
C[ (i*N) + j + 3 ] += Aik * B[ (k*N) + j + 3 ];
C[ (i*N) + j + 4 ] += Aik * B[ (k*N) + j + 4 ];
C[ (i*N) + j + 5 ] += Aik * B[ (k*N) + j + 5 ];
C[ (i*N) + j + 6 ] += Aik * B[ (k*N) + j + 6 ];
C[ (i*N) + j + 7 ] += Aik * B[ (k*N) + j + 7 ];
C[ (i*N) + j + 8 ] += Aik * B[ (k*N) + j + 8 ];
C[ (i*N) + j + 9 ] += Aik * B[ (k*N) + j + 9 ];
C[ (i*N) + j + 10 ] += Aik * B[ (k*N) + j +10 ];
C[ (i*N) + j + 11 ] += Aik * B[ (k*N) + j +11 ];
C[ (i*N) + j + 12 ] += Aik * B[ (k*N) + j +12 ];
C[ (i*N) + j + 13 ] += Aik * B[ (k*N) + j +13 ];
C[ (i*N) + j + 14 ] += Aik * B[ (k*N) + j +14 ];
C[ (i*N) + j + 15 ] += Aik * B[ (k*N) + j +15 ];
}
for (int l = j; l < N; l ++) {
C[ (i*N) + l ] += Aik * B[ (k*N) + l ];
}
}
}
}
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;
// pthread_create(&thread, NULL, mat_mul_thread, NULL);
// pthread_join(thread, NULL);
pthread_t * threads;
threads = (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(&threads[i], NULL, mat_mul_thread, pid);
}
for (int i = 0; i < num_threads; i++) {
pthread_join(threads[i], NULL);
}
}