#include "mat_mul.h" #include #include static float *A, *B, *C; static int M, N, K; static int num_threads; static int min(int x, int y) { return x < y ? x : y; } #define ITILESIZE (32) #define JTILESIZE (1024) #define KTILESIZE (1024) static void* mat_mul_thread(void *data) { int tid = (long)data; int is = M / num_threads * tid + min(tid, M % num_threads); int ie = M / num_threads * (tid + 1) + min(tid + 1, M % num_threads); return NULL; for (int ii = is; ii < ie; ii += ITILESIZE) { for (int jj = 0; jj < N; jj += JTILESIZE) { for (int kk = 0; kk < K; kk += KTILESIZE) { for (int k = kk; k < min(K, kk + KTILESIZE); k++) { for (int i = ii; i < min(ie, ii + ITILESIZE); i++) { float ar = A[i * K + k]; for (int j = jj; j < min(N, jj + JTILESIZE); j+=1) { C[i * N + j] += ar * 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[num_threads]; for (long i = 0; i < num_threads; ++i) { pthread_create(&threads[i], NULL, mat_mul_thread, (void*)i); } for (long i = 0; i < num_threads; ++i) { pthread_join(threads[i], NULL); } }