#include "mat_mul.h" #include #include #include static float *A, *B, *C; static int M, N, K; static int num_threads; #define min(a, b) (((a) < (b)) ? (a) : (b)) #define BLOCKSIZE 45 static void* mat_mul_thread(void *data) { int pid = * (int *) data; int slice = M / num_threads; // 4096/20 : 204 u_int64_t start = pid * slice; //eatch thread does 204 entiries Matrix Mul start: pid*204. u_int64_t end = pid == num_threads - 1 ? M : (pid + 1) * slice; float Aik; int bs = BLOCKSIZE; for (u_int64_t kk = 0; kk < (u_int64_t)K; kk += bs) { //4ea u_int64_t mk = min(kk + bs, (u_int64_t)K); for (u_int64_t i = start; i < end; ++i) { for (u_int64_t k = kk; k < mk; ++k) { Aik = A[i * K + k]; u_int64_t mmj = (N>>3)<<3; u_int64_t j = 0; for ( ; j < mmj; j+=8) { C[i * N + j] += Aik * B[k * N + j]; 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]; } for( ; j<(u_int64_t)N; j++) { C[i * N + j] += Aik * 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 * 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); } }