【问题标题】:Parallel for_each using openmp使用 openmp 并行 for_each
【发布时间】:2011-01-05 00:29:41
【问题描述】:

当 std::sort() 与 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);
    }
}

【问题讨论】:

    标签: c++ parallel-processing openmp


    【解决方案1】:

    仅使用-D_GLIBCXX_PARALLEL 进行编译不一定会并行化所有算法(请参阅here):

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

    但是Configuration and tuning 章节可能会帮助您强制并行化。

    只是对您的“基准”的注释: std::sortstd::for_each 不一定会调用相同的次数 delay()std::for_each 调用延迟方法 N 次,std::sort 调用它介于 N log(N)N^2 次之间(参见 reference)。因此,测量执行时间只能为您提供关于并行化的微弱指示。

    【讨论】:

    • 我知道 Big-Oh,它只是为了让它慢到可以看到“top”和“time”。
    • 您的配置和调整链接有所帮助。这使得 for_each() 并行:std::for_each(foo.begin(), foo.end(), noop, _gnu_parallel::parallel_balanced);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    相关资源
    最近更新 更多