I wrote a very simple example for multithreading in C++. How comes that multithreading and single threading have approximatly the same execution time?
CODE:
#include <iostream>
#include <thread>
#include <ctime>
using namespace std;
// function adds up all number up to given number
void task(int number)
{
int s = 0;
for(int i=0; i<number; i++){
s = s + i;
}
}
int main()
{
int n = 100000000;
////////////////////////////
// single processing //
////////////////////////////
clock_t begin = clock();
task(n);
task(n);
task(n);
task(n);
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "time single-threading: "<< elapsed_secs << " sec" << endl;
////////////////////////////
// multiprocessing //
////////////////////////////
begin = clock();
thread t1 = thread(task, n);
thread t2 = thread(task, n);
thread t3 = thread(task, n);
thread t4 = thread(task, n);
t1.join();
t2.join();
t3.join();
t4.join();
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "time multi-threading: " << elapsed_secs << " sec" << endl;
}
for me the output of the program is
time single-threading: 0.755919 sec
time multi-threading: 0.746857 sec
I compile my code with
g++ cpp_tasksize.cpp -std=c++0x -pthread
And I run on a 24-core-linux-machine