c++multithreadingmultiple-arguments

Why my multithreading example takes the same amount of time as the none one?


I would like to create a few threads in my program where I pass multiple arguments. I found this example where it shows that you can avoid structs and pass multiple arguments to a thread. It worked. Or so I thought. When I looked at the duration of my functions, they took the same amount of time.

I am running my code on Amazon server, so I am not sure if the problem is with the server or my code.

EDIT I added executable code and ran it on my local machine. It doesnt seem to show good results.

    #include <iostream>
    #include <thread>
    #include <future>
    #include <unistd.h>
    #include "time.h"

    using namespace std;

    void threadCallback(float &number)
    {
        sleep(10);
        number = 10;
    }


    int main()
    {  
        clock_t begin = clock();

        for(int j = 0; j < 2; j++)
        {
            float fitness = 0;
            threadCallback(fitness);

        }

        double duration = double(clock()-begin)/CLOCKS_PER_SEC;
        std::cout << "Original duration \t\t\t" << duration << endl;

        clock_t begin1 = clock();

        float fitness1 = 0;
        std::thread th1(threadCallback, std::ref(fitness1));

        float fitness2 = 0;        
        std::thread th2(threadCallback, std::ref(fitness2));

        th1.join();
        th2.join();

        double duration1 = double(clock()-begin1)/CLOCKS_PER_SEC;
        cout << "My duration \t\t\t" << duration1 << endl;
        return 0;
}

I would appreciate any guidance as I am stuck.

The durations I get are: 0,000095 and 0,000297 respectively.


Solution

  • Multithreading is not free. Each time you spawn a thread, there is some initialization overhead. Also, having multiple threads means that the operating system needs to manage them, thus switching from one to another doesn't come for free either.

    Your problem (aka the code that needs to run on each thread) is just to small to get any performance benefit. As a general rule of thumb, I wouldn't suggest trying to parallelize any code that takes less than a few milliseconds to run, because depending on your operating system, it might be the time it takes to start another thread.

    A second problem you have is with the usage of clock(). It takes into account the time spent running your program, not the elapsed time since the beginning of your program. That's entirely different because a computer never runs a single program at once. To address that, I would suggest looking at QueryPerformanceCounter (that's Windows only). There are probably other functions that are more generic available somewhere...