86 lines
1.8 KiB
C++
86 lines
1.8 KiB
C++
|
#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 BLOCKSIZE = 48;
|
||
|
/*
|
||
|
static int min (int a, int b) {
|
||
|
if (a>b)
|
||
|
return b;
|
||
|
else
|
||
|
return a;
|
||
|
};
|
||
|
*/
|
||
|
|
||
|
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 pid = * (int *) data;
|
||
|
|
||
|
int slice = M / num_threads;
|
||
|
int start = pid * slice;
|
||
|
int end = pid == num_threads - 1 ? M : (pid + 1) * slice;
|
||
|
|
||
|
float Aik;
|
||
|
|
||
|
int bs = BLOCKSIZE;
|
||
|
int temp_k, iN, kN, iK;
|
||
|
|
||
|
// for (int ii = start; ii < end; ii += bs) {
|
||
|
for (int kk = 0; kk < K; kk += bs) {
|
||
|
if(kk+bs <= K)
|
||
|
temp_k = kk+bs;
|
||
|
else
|
||
|
temp_k = K;
|
||
|
// for (int jj = 0; jj < N; jj += bs) {
|
||
|
// for (int i = ii; i < min(ii + bs, end); ++i) {
|
||
|
for (int i = start; i < end; ++i) {
|
||
|
iK = i*K;
|
||
|
iN = i*N;
|
||
|
for (int k = kk; k < temp_k; k++) {
|
||
|
kN = k*N;
|
||
|
// for (int k = 0; k < K; k++) {
|
||
|
Aik = A[iK + k];
|
||
|
// for (int j = jj; j < min(jj + bs, N); j++)
|
||
|
for (int j = 0; j < N; j++)
|
||
|
C[iN + j] += Aik * B[kN + 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[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);
|
||
|
}
|