C++ 我如何知道OpenMP完成了多少工作;对于指令“;?
我想知道使用OpenMP的for循环的进度。 我知道还原指令不起作用,但我这样写道:C++ 我如何知道OpenMP完成了多少工作;对于指令“;?,c++,openmp,C++,Openmp,我想知道使用OpenMP的for循环的进度。 我知道还原指令不起作用,但我这样写道: #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 <&
#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
2 / 100
3 / 100
在减少
指令期间,是否有方法获得正确的总和
值?
或者我应该使用另一种方法吗?你应该使用另一种方法。reduce创建一个线程私有变量(在您的例子中是
sum
),它只在所有线程都连接时在末尾进行缩减。缩减高度依赖于实现。它可以等待所有线程完成,它可以随着线程完成而减少,它可以创建一个减少树,等等
相反,为了跟踪进度,可以使用另一个变量numDone
,每个线程都会自动增加该变量
编辑
很好地解释了这一点:
缩减(运算符|固有:列表):变量具有本地副本
在每个线程中,但将汇总本地副本的值
(减少)为全局共享变量
为了避免通信的需要(从更新共享计数器),您可以只打印线程号和它迄今为止处理的项目数,即
#pragma omp parallel
{
int count = 0;
#pragma omp for schedule(dynamic) // or whatever schedule you want
for(int i=0; i<size; ++i) {
// ...
printf("@ %d: done %d loops\n",
omp_get_thread_num(),++count); // should not need a critical section
}
}
#pragma omp并行
{
整数计数=0;
#pragma omp for schedule(dynamic)//或任何您想要的计划
对于(int i=0;i,reduce
条款有一个非常明确的含义,在第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=0
#共享(总和)计划的pragma omp(引导式)
对于(int i=0;i 这是一个棘手的问题,因为你需要在OpenMP区域中间做一个减法和。每个线程都有自己的<代码>和>代码>变量。
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;
}
}