3

为什么这段代码在与 std::sort() 完美配合时不能并行化 std::for_each()?

我如何解决它?

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

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);
    }
}
4

1 回答 1

6

仅编译-D_GLIBCXX_PARALLEL并不一定会并行化所有算法(请参见此处):

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

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

Just a note to your "Benchmark": std::sort and std::for_each won't necessarily call delay() the same number of times. std::for_each calls the delay method for N times, std::sort calls it for something between N log(N) and N^2 times (see reference). Thus measuring the execution time gives you only a weak indication about parallelization.

于 2010-01-14T12:41:26.313 回答