使用OpenMP并行执行for_each函数

4
为什么这段代码在使用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);
    }
}
1个回答

6

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

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

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

只是针对您的“基准测试”的一个说明:std::sortstd::for_each不一定会调用相同数量的delay()std::for_each调用N次延迟方法,std::sort调用N log(N)N^2次(参见参考文献)。因此,测量执行时间只能给出有限的关于并行化的指示。


我知道大O符号,只是为了让它足够慢,以便可以在“top”和“time”中看到。 - Thomas
你的配置和调整链接帮了大忙。这样就可以让for_each()函数并行化了: std::for_each(foo.begin(), foo.end(), noop, _gnu_parallel::parallel_balanced); - Thomas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接