Multithread program in C++ shows the same performance as a serial one

后端 未结 3 1879
一生所求
一生所求 2020-12-19 14:16

I just want to write a simple program in C++, which creates two threads and each of them fills vector by squares of integers (0, 1, 4, 9, ...). Here is my code:



        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-19 14:58

    Most of the suggestions are right: threading a task will improve the execution time only if the thread cpu load (in your case the multiplication i * i) is more important than the shared memory access load (in your case v.push_back). You can try with this code. You will see the gains of threading. And you can use the unix command

    >time ./a.out 
    

    to time your code more easily.

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    #define MULTI 1
    #define SIZE 10000000
    
    void fill(std::vector &v, size_t n)
    {
        int sum = 0;
        for (size_t i = 0; i < n; ++i) {
            for (size_t j = 0; j < 100; ++j) {
                sum += sqrt(i*j);
            }
        }
        v.push_back(sum);
    }
    
    int main()
    {
        std::vector v1, v2;
        v1.reserve(SIZE);
        v2.reserve(SIZE);
        #if !MULTI
        fill(v1, SIZE);
        fill(v2, SIZE);
        #else
        std::thread first(fill, std::ref(v1), SIZE);
        std::thread second(fill, std::ref(v2), SIZE);
    
        first.join();
        second.join();
        #endif
        return 0;
    }
    

提交回复
热议问题