打开应用于while循环的mp
open mp applied to while loop
我已经得到了以下递归代码,我正在尝试并行使用c++打开mp库。目前,我刚刚在循环之前添加了#pragma omp parallel子句(因为visual studio只支持omp 2.0,所以我不能使用任务),但它实际上减慢了速度。我做错了什么?
Ok。根据您关于使用omp节的建议,我已经重写了我的代码。现在看起来是这样的。但是,它仍然比顺序版本慢。
long long p (long long n, long long mmm)
{
long long c = 0;
long exponent = 0;
double ex;
long counter = 1;
long long ttt = 0;
long long ttt1 = 0;
long long b = 0;
long long a = 0;
long long h = 0;
while (counter > 0)
{
ex = pow(-1, counter - 1);
exponent = (long) ex;
ttt = (n - ( (counter * ( (3 * counter) - 1)) / 2));
ttt1 = (n - ( (counter * ( (3 * counter) + 1)) / 2));
#pragma omp parallel sections
{
#pragma omp section
{
if (ttt == 0 || ttt == 1)
{
a = exponent * 1;
c = c + a;
}
else if (ttt>0)
{
a = exponent * p((n - ( (counter * ( (3 * counter) - 1)) / 2)), mmm);
c = c + a;
}
}
#pragma omp section
{
//If n == 1 or 0 return 1 as per convention else do the calculation
if (ttt1 == 0 || ttt1 == 1)
{
b = exponent * 1;
c = c + b;
}
else if (ttt1 > 0)
{
b = exponent * p( (n - ( (counter * ( (3 * counter) + 1)) / 2)), mmm);
c = c + b;
}
}
}
if (ttt < 0 && ttt1 < 0)
break;
++counter;
}
#pragma omp parallel
定义了一部分将并行运行的代码。这意味着你将对整个while
循环进行多次并行运行,而不是对单个循环的迭代进行并行运行。
这意味着OpenMP在管理对变量的并发读/写访问方面有很大的开销,因此总运行时间更大。
如果你打算并行计算a
和b
,你可能应该把整个if ... else if ... else
标记为omp section
,假设它们是完全独立的计算。
循环的自动并行化只能通过for
循环和#pragma omp parallel for
来实现。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 打开 MP 三用于减少的循环
- 开放MP;嵌套循环之间的操作
- 我如何将这个循环与开放的mp并行
- 使用 Open MP 并行"for"循环读取和写入数据结构
- 打开应用于while循环的mp