gpt4 book ai didi

c++ - 我怎么知道在 OpenMP "for directive"中完成了多少作业?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:23:58 24 4
gpt4 key购买 nike

我想知道使用 OpenMP 的 for 循环的进度。我知道 reduction 指令不起作用,但我是这样写的:

#pragma omp for reduction (+:sum)
for (int i=0; i < size; i++){
// do something that takes about 10seconds
sum++;
#pragma omp critical
cout << sum << " / " << size << endl;
}

这将返回如下内容:

1 / 100
1 / 100
2 / 100
1 / 100
...

但我想要这个:

1 / 100
2 / 100
3 / 100

. ..

reduction 指令中有没有办法得到正确的 sum 值?还是应该使用其他方法?

最佳答案

reduction 子句具有非常明确的含义,在 latest OpenMP standard 的第 2.9.3.6 节中有详细解释。 .我怀疑您能否将其用于上述目的。

无论如何,只需稍微修改您的源代码就可以实现该行为:

sum = 0
#pragma omp for shared(sum) schedule(guided)
for (int i=0; i < size; i++){
// do something that takes about 10seconds
#pragma omp critical(PRINT)
{
sum++;
cout << sum << " / " << size << endl;
}
}

通过这种方式,您可以确保一次只有一个线程尝试递增“sum”并将其打印在屏幕上。考虑到每次迭代需要很长时间,这种同步应该不会引起性能问题。

关于c++ - 我怎么知道在 OpenMP "for directive"中完成了多少作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12436132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com