使用openmp并行for_each

Tho*_*mas 3 c++ parallel-processing openmp

为什么这个代码在与std :: sort()完全正常工作时不会并行化std :: for_each()?

我如何解决它?

g++ -fopenmp -D_GLIBCXX_PARALLEL=1 -o p p.cc && time ./p  sort
Run Code Online (Sandbox Code Playgroud)

Linux上的GCC 4.3.

#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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Mr.*_*Mr. 6

只是编译-D_GLIBCXX_PARALLEL并不一定并行化所有算法(见这里):

请注意,这并不一定意味着所有内容最终都会以并行方式执行,而是编码到并行版本中的启发式和设置将用于确定是否将使用所有,部分或无法执行所有算法并行变体.

但是,配置和调优章节可能会帮助您强制并行化.

只需记下您的"基准": std::sort并且std::for_each不一定会拨打delay()相同的次数.std::for_each在时间上调用延迟方法,在N时间和时间std::sort之间调用它(参见参考资料).因此,测量执行时间只会给出关于并行化的弱指示.N log(N)N^2