75 lines
1.8 KiB
C++
75 lines
1.8 KiB
C++
#include "mat_mul.h"
|
|
|
|
#include <cstdlib>
|
|
#include <cstdio>
|
|
#include <pthread.h>
|
|
|
|
#define THREAD_MAX 80
|
|
#define UNROL_SIZE 8
|
|
#define BLOCK_SIZE 45
|
|
|
|
static float *A, *B, *C;
|
|
static int M, N, K;
|
|
static int num_threads;
|
|
|
|
pthread_t threads[THREAD_MAX];
|
|
int threadId[THREAD_MAX];
|
|
|
|
__inline 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
|
|
int tid = *(int*)data;
|
|
int unit = M / num_threads;
|
|
int st = tid*unit;
|
|
int ed = tid == num_threads - 1 ? M : (tid+1)*unit;
|
|
|
|
for (int kk = 0; kk < K; kk += BLOCK_SIZE) {
|
|
for (int i = st; i < ed; ++i) {
|
|
for (int k = kk; k < min(kk+BLOCK_SIZE,K); ++k) {
|
|
float Aik = A[i * K + k];
|
|
int j;
|
|
for (j = 0; j < (N/UNROL_SIZE)*UNROL_SIZE; j+=UNROL_SIZE) {
|
|
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 < 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
|
|
|
|
for(int i = 0; i < num_threads; i++)
|
|
{
|
|
threadId[i] = i;
|
|
pthread_create(&threads[i], NULL, mat_mul_thread, &threadId[i]);
|
|
}
|
|
|
|
for(int i = 0; i < num_threads; i++)
|
|
{
|
|
pthread_join(threads[i], NULL);
|
|
}
|
|
}
|