multi-threading not improving performance in recursive c++ program
consider this recursive multi-threaded program :
#include <iostream>
#include <thread>
#define NUMTHREADS 4
using namespace std;
int g[NUMTHREADS];
thread t[NUMTHREADS];
void task1(int x)
{
if(x+1<NUMTHREADS)
t[x] = thread(task1, x+1);
for(int i=0;i<100000000;i++)
g[x]++;
if(x+1<NUMTHREADS)
t[x].join();
}
int main()
{
task1(0);
for(int i=0;i<NUMTHREADS;i++)
cout<<g[i]<<" ";
}
I'm expecting the thread overhead to be insignificant but in fact the
runtime of the program increases linearly with the number of threads.
Here's some timings on my 6-core cpu:
NUMTHREADS = 1:
$ time ./a
100000000
real 0m0.330s
user 0m0.312s
sys 0m0.015s
NUMTHREADS = 2:
$ time ./a
100000000 100000000
real 0m0.742s
user 0m1.404s
sys 0m0.015s
NUMTHREADS = 3:
$ time ./a
100000000 100000000 100000000
real 0m1.038s
user 0m2.792s
sys 0m0.000s
NUMTHREADS = 4:
$ time ./a
100000000 100000000 100000000 100000000
real 0m1.511s
user 0m5.616s
sys 0m0.015s
Any idea why this might be?
No comments:
Post a Comment