C ++ multi-threaded program shows the same performance as serial

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

#include <iostream>
#include <vector>
#include <functional>
#include <thread>
#include <time.h>

#define MULTI 1
#define SIZE 10000000

void fill(std::vector<unsigned long long int> &v, size_t n)
{
    for (size_t i = 0; i < n; ++i) {
        v.push_back(i * i);
    }
}

int main()
{
    std::vector<unsigned long long int> v1, v2;
    v1.reserve(SIZE);
    v2.reserve(SIZE);
    #if !MULTI
    clock_t t = clock();
    fill(v1, SIZE);
    fill(v2, SIZE);
    t = clock() - t;
    #else
    clock_t t = clock();
    std::thread first(fill, std::ref(v1), SIZE);
    fill(v2, SIZE);
    first.join();
    t = clock() - t;
    #endif
    std::cout << (float)t / CLOCKS_PER_SEC << std::endl;
    return 0;
}

But when I run my program, I see that there is no significant difference between the serial version and the parallel version (or sometimes the parallel version shows even worse results). Any idea what is going on?

+4
source share
3 answers

When I execute your code from MSVC2015 to i7, I notice:

  • 14 26 . . .
  • 0,3 0,2 , , .

, , fill() .

, fill() (, ), . , , , , .

:

, , , , , , , doug , (.. ).

, , , , , ( ):

enter image description here

:

// computation intensive
void mytask(unsigned long long loops)
{
    volatile double x; 
    for (unsigned long long i = 0; i < loops; i++) {
        x = sin(sqrt(i) / i*3.14159);
    }
}

//memory intensive
void mytask2(vector<unsigned long long>& v, unsigned long long loops)
{
    for (unsigned long long i = 0; i < loops; i++) {
        v.push_back(i*3+10);
    }
}
+2

, , , , .

, . std::this_thread::sleep_for

0

: , ( * i) ( v.push_back). . . unix

>time ./a.out 

.

#include <iostream>
#include <vector>
#include <functional>
#include <thread>
#include <time.h>
#include <math.h>

#define MULTI 1
#define SIZE 10000000

void fill(std::vector<unsigned long long int> &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<unsigned long long int> 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;
}
0

Source: https://habr.com/ru/post/1629707/


All Articles