63 lines
1.4 KiB
C++
63 lines
1.4 KiB
C++
#include "mat_mul.h"
|
|
|
|
#include <cstdlib>
|
|
#include <cstdio>
|
|
#include <pthread.h>
|
|
#include <immintrin.h>
|
|
|
|
static float *A, *B, *C;
|
|
static int M, N, K;
|
|
static int num_threads;
|
|
|
|
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
|
|
|
|
#ifdef __AVX512F__
|
|
#define IBS 64
|
|
#define KBS 40
|
|
#else
|
|
#define IBS 32
|
|
#define KBS 32
|
|
#endif
|
|
|
|
static void* mat_mul_thread(void *data) {
|
|
const int m = M / num_threads;
|
|
const int tid = *((int *) data);
|
|
const int begin = (tid * m);
|
|
const int end = (tid == num_threads - 1) ? M : (tid + 1) * m;
|
|
float Aik;
|
|
|
|
for (int ii = begin; ii < end; ii += IBS) {
|
|
for (int kk = 0; kk < K; kk += KBS) {
|
|
for (int i = ii; i < MIN(ii + IBS, end); ++i) {
|
|
for (int k = kk; k < MIN(kk + KBS, K); ++k) {
|
|
Aik = A[i * K + k];
|
|
for (int j = 0; 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;
|
|
|
|
pthread_t *threads;
|
|
threads = (pthread_t *) malloc(sizeof(pthread_t) * num_threads);
|
|
|
|
for (int i = 0; i < num_threads; ++i) {
|
|
int *tid = (int *) malloc(sizeof(int));
|
|
*tid = i;
|
|
pthread_create(&threads[i], NULL, mat_mul_thread, tid);
|
|
}
|
|
|
|
for (int i = 0; i < num_threads; ++i) {
|
|
pthread_join(threads[i], NULL);
|
|
}
|
|
}
|