由一维数组模拟二维数组的方式进行矩阵相乘操作
单线程操作:
#include <iostream>
using namespace std;
void func(int* A, int* B, int* C, int M, int P, int N) {
// C(M,P) = A(M,N) * B(N,P)
for (int i = 0; i < M; ++i) {
for (int j = 0; j < P; ++j) {
C[i * P + j] = 0;
for (int k = 0; k < N; ++k) {
C[i * P + j] += A[i * N + k] * B[k * P + j];
}
}
}
}
void printM(int* juzhen, int M, int N) {
// print A(M,N)
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++)
cout << juzhen[i * N + j] << " ";
cout << endl;
}
cout << endl;
}
const int M = 3, N = 3, P = 3;
int A[M * N], B[N * P], C[M * P]; //定义矩阵ABC
int main() {
for (int i = 0; i < M * N; i++) A[i] = i;
for (int i = 0; i < N * P; i++) B[i] = i;
func(A, B, C, M, P, N);
printM(A, M, N);
printM(B, N, P);
printM(C, M, P);
return 0;
}
多线程操作:
#include <windows.h>
#include <iostream>
#include <ctime>
using namespace std;
struct MYDATA {
int begin, end;
int* A, * B, * C;
int P, N;
};
DWORD ThreadProc(LPVOID IpParam) {
MYDATA* pmd = (MYDATA*)IpParam;
int* A = pmd->A, * B = pmd->B, * C = pmd->C;
int begin = pmd->begin, end = pmd->end, P = pmd->P, N = pmd->N;
for (int index = begin; index < end; index++) {
int i = index / P, j = index % P;
C[i * P + j] = 0;
for (int k = 0; k < N; ++k) {
C[i * P + j] += A[i * N + k] * B[k * P + j];
}
}
return 0;
}
void func(int* A, int* B, int* C, int M, int P, int N) {
// C(M,P) = A(M,N) * B(N,P)
for (int i = 0; i < M; ++i) {
for (int j = 0; j < P; ++j) {
C[i * P + j] = 0;
for (int k = 0; k < N; ++k) {
C[i * P + j] += A[i * N + k] * B[k * P + j];
}
}
}
}
void printM(int* A, int row, int col) {
// print A(M,N)
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
cout << A[i * col + j] << " ";
cout << endl;
}
cout << endl;
}
const int M = 2000, N = 2000, P = 2000;
int A[M * N], B[N * P], C[M * P];
int main() {
clock_t startTime, endTime;
startTime = clock();//计时开始
for (int i = 0; i < M * N; i++) A[i] = i;
for (int i = 0; i < N * P; i++) B[i] = i;
// ----------------------------------- 多线程
const int m = 4;
HANDLE hThread[m];
static MYDATA mydt[m];
int temp = (M * P) / m;
for (int i = 0; i < m; ++i) {
mydt[i].A = A, mydt[i].B = B, mydt[i].C = C;
mydt[i].begin = i * temp, mydt[i].end = i * temp + temp, mydt[i].P = P, mydt[i].N = N;
if (i == m - 1) // 最后一个线程计算剩余的
mydt[i].end = M * P;
hThread[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc, &mydt[i], 0, NULL);
}
WaitForMultipleObjects(m, hThread, TRUE, INFINITE);
// ----------------------------------- 串行
//func(A, B, C, M, P, N);
// printM(A, M, N);
// printM(B, N, P);
// printM(C, M, P);
endTime = clock();//计时结束
cout << "use time: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << endl;
return 0;
}