#include "mat_mul.h" #include #include #include static float *A, *B, *C; static int M, N, K; static int num_threads; static int slice; static void* mat_mul_thread(void *data) { //// TODO: parallelize & optimize matrix multiplication int pid = * (int *) data; int start = pid * slice; int end = ( pid == num_threads - 1 ) ? M : (pid + 1) * slice; int bs = 32; for (int kk=0; kk < K; kk+=bs) { int row_A = start * K; int row_C = start * N; for (int i= start; i < end; ++i) { for (int k=kk; k < ((kk+bs < K)? kk+bs : K); ++k){ for (int j=0; j < N; ++j) { C[row_C + j] += A[row_A + k] * B[k * N + j]; } } row_A += K; row_C += N; } } 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 if (M < num_threads) num_threads = M; slice = M / num_threads; pthread_t* threads; threads = (pthread_t*)malloc((num_threads) * sizeof(pthread_t)); for (int i=0; i < num_threads; ++i) { int * pid = (int *) malloc(sizeof(int)); *pid = i; pthread_create(&threads[i], NULL, mat_mul_thread, (void*)pid); } for(int i=0; i < num_threads; ++i) pthread_join (threads[i], NULL); }