我创建了一个非常简单的测试程序,计算一些标量c和矩阵A的c*A。您可以在此处在线运行它,或将以下代码粘贴到您最喜欢的文本编辑器中:
#include <iostream>
#include <time.h>
#include <chrono>
#include <thread>
void fill_rand_matrix(double* mat, int n){
for (int i=0;i<n;i++){
mat[i]=static_cast <double> (rand()) / static_cast <double> (RAND_MAX)*20-10;
}
}
void test(size_t m, size_t n, double alpha, double* X) {
for (int j = 0; j < m; ++j) {
for (int i = 0; i < n; ++i) {
X[i+ j*n] *= alpha;
}
}
}
int main()
{
int m=10000;
int n=10000;
double res_scaling=0.5;
double* res=new double[m*n];
fill_rand_matrix(res,n*m);
auto begin1 = std::chrono::steady_clock::now();
std::thread t1(test,0.5*m,n,res_scaling,res);
std::thread t2(test,0.5*m,n,res_scaling,(double*)(res+(m/2)*n));
t1.join();
t2.join();
auto end1= std::chrono::steady_clock::now();
std::cout << "Time taken multithreaded = " << std::chrono::duration_cast<std::chrono::milliseconds>(end1 - begin1).count() << "[ms]" << std::endl;
auto begin2 = std::chrono::steady_clock::now();
test(m,n,res_scaling,res);
auto end2= std::chrono::steady_clock::now();
std::cout << "Time taken singlethreaded = " << std::chrono::duration_cast<std::chrono::milliseconds>(end2 - begin2).count() << "[ms]" << std::endl;
return 0;
}
当我多次运行这段代码时,多线程版本要么只比单线程版本稍微快一点,要么甚至比单线程版本更慢。即使我添加了超过2个线程,这种情况仍然会发生。即使问题几乎可以完美地按照核心数进行扩展,多线程似乎并没有任何好处。
此外,我设置的矩阵大小越大,运行时间的波动就越大,有时甚至相差20倍。
您知道这里发生了什么吗?