计算机执行矩阵相乘时,如果直接按照3层循环执行,会很慢。使用多线程,可以缩短时间。下面的代码先执行了不带多线程的原始版本,然后用多线程技术再执行了一遍,然后输出了他们的执行时间。
#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
using namespace std;
typedef vector<vector<int>> Matrix;
// 主函数进行多线程矩阵乘法
Matrix matrixMultiplyMultiThread(const Matrix& A, const Matrix& B, int numThreads) {
int rowsA = A.size();
int colsA = A[0].size();
int colsB = B[0].size();
Matrix result(rowsA, vector<int>(colsB, 0)); // 初始化结果矩阵
vector<thread> threads;// 创建线程
int rowsPerThread = rowsA / numThreads;
for (int k = 0; k < numThreads; ++k) {
int startRow = k * rowsPerThread;
int endRow = (k == numThreads - 1) ? rowsA : startRow + rowsPerThread; // 最后一个线程把剩下的行全处理掉
threads.emplace_back([&result, &A, &B, &colsA, &colsB, startRow, endRow]() {
for (int i = startRow; i < endRow; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {//直接挪到最外层,可以避免cache-miss
result[i][j] += A[i][k] * B[k][j];
}
}
}
});
}
for (auto& th : threads) {
if (th.joinable()) { // 等待所有线程完成
th.join();
}
}
return result;
}
// 原始矩阵乘法
Matrix matrixMultiplyOrigin(const Matrix& A, const Matrix& B) {
int rowsA = A.size();
int colsA = A[0].size();
int colsB = B[0].size();
Matrix result(rowsA, vector<int>(colsB, 0)); // 初始化结果矩阵
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
}
int main() {
int sz = 1000;
int m = sz, n = sz, p = sz; // 矩阵大小
Matrix A(m, vector<int>(n, 1));
Matrix B(n, vector<int>(p, 1));
// 测试原始版本
auto start = chrono::high_resolution_clock::now();
Matrix C = matrixMultiplyOrigin(A, B);
auto end = chrono::high_resolution_clock::now();
chrono::duration<double> duration = end - start;
cout << "Original version time: " << duration.count() << " seconds" << endl;
// 测试多线程版本
int numThreads = thread::hardware_concurrency(); // 获取可用线程数,我的Mac电脑是8
cout << "numThreads is " << numThreads << endl;
start = chrono::high_resolution_clock::now();
C = matrixMultiplyMultiThread(A, B, numThreads);
end = chrono::high_resolution_clock::now();
duration = end - start;
cout << "Multithreaded version time: " << duration.count() << " seconds" << endl;
return 0;
}
结果是:
Original version time: 20.0384 seconds
numThreads is 8
Multithreaded version time: 5.45786 seconds
可以看到,当矩阵维度是1000时,多线程可以大大缩短矩阵乘法运算时间。
注①:线程本身的创建和销毁也是花时间的,并且操作系统能支持的线程数受硬件影响,当使用的线程数大于系统能提供的线程数时,操作系统会通过时间片轮转(时间片调度)来切换这些线程。这意味着在某一时刻,只有一部分线程可以运行,其他线程则处于等待状态。这可能会导致线程之间的竞争和上下文切换,增加 CPU 的调度开销。所以线程并不是越多效果越好。
注②:现在的版本会有cache-miss的问题,详情可以参考我的另一篇文章:矩阵相乘_重排序优化算法的C++实现。