I have created a very simple test program that calculates c*A of some scalar c and matrix A. You can either run it online here here or paste the following code in your favorite text editor:
#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;
}
When I am running this code multiple times, the multithreaded version is either only faster marginally or even slower than the singlethreaded variant. This even happens, if I add more than 2 threads. There appears to be just no benefit in multithreading even though the problem should almost scale perfectly with the number of cores. In addition, the higher I set the matrix size, the more wildly the running times oscillate, sometimes by as much as a factor of twenty.
Do you have any idea what is happening here?