gpt4 book ai didi

c++ - OpenMP 嵌套循环索引依赖

转载 作者:太空宇宙 更新时间:2023-11-04 11:25:54 25 4
gpt4 key购买 nike

我是这个特定堆栈交换的新手。我不知道使事情看起来漂亮的语法,抱歉。

我正在努力为一个娱乐项目最大化我的代码。我用 C++ 编写代码,并使用 OpenMP 进行并行化。问题如下,这是实际代码的简化版本,假设我有:

 //Lots of other stuff

#pragma omp parallel for ordered num_threads(4) schedule(dynamic, 100) private(a,b)
for(int a=0; a<230000; a++)
{
for(int b=a+1; b<230000; b++)
{

//code increments b at times, example
while(stored[b][0]==stored[a][0])
{
b++;
}

//increment counter
#pragma omp atomic
++counter;

//counting part
#pragma omp ordered
if(stored[a][0]!=stored[b][0])
{
if(stored[a][1]!=stored[b][1])
{
//print counter to file
}
}
}
}

本质上,我想计算我的代码运行的次数。但是,依赖项“b=a+1”似乎使代码偏离了方向。它给我的计数就好像它只是“b=0”一样,大约是 100 亿。

如有任何帮助,我们将不胜感激。

编辑 1: 我应该提到循环内的所有内容都独立于 a。即它可以在a上任意方向或a的任意随机值上运行,但在b上必须是有序的。重点是在某些约束下跳过尽可能多的 b 值,b 中的增量是衡量的,为此算法需要 b 中的顺序。

最佳答案

我对你的代码有点困惑。如果您试图使代码并行,为什么要在 pragma for 中放置 ordered ? Ordered 将使它串行运行。如果您使用 ordered 得到错误的答案,则您的代码的其他部分可能是错误的。

我发现的一个问题是您在 pragma 语句之前声明了 a 和 b。您可能不应该这样做,这样您的代码就不会混淆。 a 和 b 应该在 for 循环的范围内。

这是我认为您正在寻找的代码。

// do not declare a or b in the code before or use different variables instead of a or b
int counter = 0;
#pragma omp parallel for num_threads(4) schedule(dynamic, 100)
for(int a=0; a<230000; a++)
{
int tmpCounter = 0;
for(int b=a+1; b<230000; b++)
{

//code increments b at times, example
while(stored[b][0]==stored[a][0])
{
b++;
}

//increment counter code
++tmpCounter;

//counting part
// idk if you need this code to be ordered?
if(stored[a][0]!=stored[b][0])
{
if(stored[a][1]!=stored[b][1])
{
//print counter to file
}
}

}
#pragma omp critical
counter += tmpCounter;
}

如果这不是您要查找的内容,请在澄清后评论我的帖子。我会尝试修复它。

关于c++ - OpenMP 嵌套循环索引依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26695615/

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