95 lines
1.9 KiB
C++
95 lines
1.9 KiB
C++
#include "mat_mul.h"
|
|
|
|
#include <cstdlib>
|
|
#include <cstdio>
|
|
#include <pthread.h>
|
|
|
|
#ifndef MIN
|
|
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
|
|
#endif
|
|
|
|
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
|
|
|
|
// for (int i = 0; i < M; ++i) {
|
|
// for (int j = 0; j < N; ++j) {
|
|
// for (int k = 0; k < K; ++k) {
|
|
// C[i * N + j] += A[i * K + k] * B[k * N + j];
|
|
// }
|
|
// }
|
|
// }
|
|
|
|
int tid ;
|
|
int start_M ;
|
|
int end_M ;
|
|
|
|
int p_size ;
|
|
int block = 32 ;
|
|
float A_temp;
|
|
|
|
tid = *((int*)data) ;
|
|
|
|
if( (M%num_threads) != 0 ) {
|
|
p_size = (M/num_threads) + 1 ;
|
|
if(tid!=(num_threads-1)) {
|
|
start_M = tid * p_size;
|
|
end_M = start_M + p_size ;
|
|
}
|
|
else {
|
|
start_M = tid * p_size;
|
|
end_M = M ;
|
|
}
|
|
}
|
|
else {
|
|
p_size = (M/num_threads) ;
|
|
start_M = tid * p_size;
|
|
end_M = start_M + p_size ;
|
|
}
|
|
|
|
|
|
for (int kk = 0; kk < K; kk += block) {
|
|
for (int i = start_M; i < end_M; i++) {
|
|
for (int k = kk; k < MIN(kk+block, K); ++k) {
|
|
|
|
A_temp = A[i * K + k];
|
|
for (int j = 0; j < N; ++j) {
|
|
C[i * N + j] += A_temp * 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
|
|
|
|
int p_threads ;
|
|
|
|
int tid[num_threads] ;
|
|
|
|
pthread_t thread[num_threads];
|
|
|
|
for(p_threads = 0; p_threads<num_threads; p_threads++) {
|
|
tid[p_threads] = p_threads ;
|
|
}
|
|
|
|
for(p_threads = 0; p_threads<num_threads; p_threads++) {
|
|
pthread_create(&thread[p_threads], NULL, mat_mul_thread, &tid[p_threads]);
|
|
}
|
|
|
|
for(p_threads = 0; p_threads<num_threads; p_threads++) {
|
|
pthread_join ( thread[p_threads], NULL);
|
|
}
|
|
|
|
}
|