Parallel for_each using openmp

Why doesn't this code parallelize std :: for_each () when it works fine with std :: sort ()?

How to fix it?

g++ -fopenmp -D_GLIBCXX_PARALLEL=1 -o p p.cc && time ./p  sort

GCC 4.3 for Linux.

#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>

void delay()
{
        for(int c = 0; c < 1000000; c++) {
    }
}

int lt(int a, int b)
{
        delay();
        return a < b;
}

void noop(int a)
{
    delay();
}

int main(int argc, char **argv)
{
        if (argc < 2) {
                printf("%s  <sort | for_each>\n", argv[0]);
                return 1;
    }

        std::vector<int> foo(10000);

        if (!strcmp(argv[1], "sort")) {
        std::sort(foo.begin(), foo.end(), lt);
    } else if (!strcmp(argv[1], "for_each")) {
                std::for_each(foo.begin(), foo.end(), noop);
    }
}
+3
source share
1 answer

Just compiling with -D_GLIBCXX_PARALLELdoes not necessarily parallel all the algorithms (see here ):

Please note that this does not necessarily mean that everything will be executed in parallel, but rather that heuristics and settings encoded in parallel versions will be used to determine whether all, some or no algorithms will be executed using parallel options.

.

"": std::sort std::for_each delay() . std::for_each N , std::sort - N log(N) N^2 (. reference). , .

+6

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


All Articles