gpt4 book ai didi

C++ openmp比串行实现慢得多

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:55:55 25 4
gpt4 key购买 nike

我正在对二维阵列进行热力学模拟。该数组为 1024x1024。 while 循环迭代指定的次数或直到 goodTempChange 为 false。 goodTempChange 根据 block 的温度变化是否大于定义的 EPSILON 值设置为真或假。如果阵列中的每个 block 都低于该值,则板处于停滞状态。该程序有效,我的代码没有问题,我的问题是串行代码绝对把 openmp 代码吹得一塌糊涂。我不知道为什么。我已经尝试删除除平均计算之外的所有内容,平均计算只是您想要的方 block 周围上下左右 4 个 block 的平均值,但它仍然被串行代码破坏。我以前从未做过 openmp,我在网上查找了一些东西来做我所拥有的。我以我认为可能的最有效方式在关键区域内拥有变量,我没有竞争条件。我真的不明白有什么问题。任何帮助将不胜感激。谢谢。

while(iterationCounter < DESIRED_ITERATIONS && goodTempChange) {
goodTempChange = false;
if((iterationCounter % 1000 == 0) && (iterationCounter != 0)) {
cout << "Iteration Count Highest Change Center Plate Temperature" << endl;
cout << "-----------------------------------------------------------" << endl;
cout << iterationCounter << " "
<< highestChange << " " << newTemperature[MID][MID] << endl;
cout << endl;
}

highestChange = 0;

if(iterationCounter != 0)
memcpy(oldTemperature, newTemperature, sizeof(oldTemperature));

for(int i = 1; i < MAX-1; i++) {
#pragma omp parallel for schedule(static)
for(int j = 1; j < MAX-1; j++) {
bool tempGoodChange = false;
double tempHighestChange = 0;
newTemperature[i][j] = (oldTemperature[i-1][j] + oldTemperature[i+1][j] +
oldTemperature[i][j-1] + oldTemperature[i][j+1]) / 4;

if((iterationCounter + 1) % 1000 == 0) {
if(abs(oldTemperature[i][j] - newTemperature[i][j]) > highestChange)
tempHighestChange = abs(oldTemperature[i][j] - newTemperature[i][j]);
if(tempHighestChange > highestChange) {
#pragma omp critical
{
if(tempHighestChange > highestChange)
highestChange = tempHighestChange;
}
}
}
if(abs(oldTemperature[i][j] - newTemperature[i][j]) > EPSILON
&& !tempGoodChange)
tempGoodChange = true;

if(tempGoodChange && !goodTempChange) {
#pragma omp critical
{
if(tempGoodChange && !goodTempChane)
goodTempChange = true;
}
}
}
}
iterationCounter++;
}

最佳答案

尝试摆脱那些关键部分可能会有所帮助。例如:

#pragma omp critical
{
if(tempHighestChange > highestChange)
{
highestChange = tempHighestChange;
}
}

在这里,您可以将每个线程计算的 highestChange 存储在一个局部变量中,并在并行部分完成时,获取您拥有的 highestChange 的最大值.

关于C++ openmp比串行实现慢得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19150804/

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