我无法访问或打印嵌套for循环中的任何数据。这是我第一次编写MPI程序,并且所有示例都没有显示比Hello World更复杂的内容。我做错了什么?
void assignStarsToClusters(double *stars, double *clusters, int *azimuth)
{
ostringstream oss;
oss.str("");
oss.clear();
//double start = MPI_Wtime();
// Assign a star to the closest cluster
double smallDistance;
double tmpDistance;
int indice = 0;
MPI_Barrier(MPI_COMM_WORLD);
MPI_Bcast(azimuth /*the data we're broadcasting*/,
NUMOFLINES /*the data size */,
MPI_INT /*the data type */,
0 /*the process we're broadcasting from */,
MPI_COMM_WORLD);
MPI_Bcast(stars /*the data we're broadcasting*/,
NUMOFSTARCOORD /*the data size */,
MPI_DOUBLE /*the data type */,
0 /*the process we're broadcasting from */,
MPI_COMM_WORLD);
MPI_Bcast(clusters /*the data we're broadcasting*/,
NUMOFCLUST /*the data size */,
MPI_DOUBLE /*the data type */,
0 /*the process we're broadcasting from */,
MPI_COMM_WORLD);
MPI_Bcast(&NUMOFCLUST /*the data we're broadcasting*/,
1 /*the data size */,
MPI_DOUBLE /*the data type */,
0 /*the process we're broadcasting from */,
MPI_COMM_WORLD);
MPI_Bcast(&NUMOFSTARCOORD /*the data we're broadcasting*/,
1 /*the data size */,
MPI_DOUBLE /*the data type */,
0 /*the process we're broadcasting from */,
MPI_COMM_WORLD);
int sx = NUMOFSTARCOORD/comm_sz;
int s_lower = my_rank * sx;
int s_upper = s_lower + sx;
for(int a = my_rank; a <= comm_sz; a++)
{
for(int i = s_lower; i <= s_upper; i+=3)
{
smallDistance = sqrt(sqr(stars[i] - clusters[0]) + sqr(stars[i+1] - clusters[1]) + sqr(stars[i+2] - clusters[2]));
indice = 0;
for(int j = 3; j <= (NUMOFCLUST * 3); j+=3)
{
tmpDistance = sqrt(sqr(stars[i] - clusters[j]) + sqr(stars[i+1] - clusters[j+1]) + sqr(stars[i+2] - clusters[j+2]));
oss << " " << j;
if(tmpDistance < smallDistance)
{
smallDistance = tmpDistance;
indice = j;
}
}
azimuth[i/3] = indice / 3;
//oss << " " << indice;
}
}
MPI_Barrier(MPI_COMM_WORLD);
// cout << oss.str() << endl;
//oss.str("");
//oss.clear();
//if(my_rank == 0)
//{
//for (int i = 0; i < NUMOFLINES; i++) {
// oss << " " << azimuth[i];
//}
//}
cout << oss.str() << endl;
//cout << "Total Time: " << MPI_Wtime() - start << endl;
}
答案 0 :(得分:0)
我会在你的MPI代码中告诉你我的错误。
MPI_Barrier():大多数情况下从不需要:MPI_Bcast()
同步是隐式的 - 当您需要与外部事物同步时需要屏障,例如在向stdout命令I / O时。
这个循环:
for(int a = my_rank; a <= comm_sz; a++)
目的尚不清楚。我希望my_rank
和comm_sz
已正确初始化。你确定他们是吗?你用mpirun正确运行代码了吗?但最重要的是:我不知道为什么,但我觉得你认为这个循环是并行化的。循环中不使用a
循环变量(其名称是一个可怕的选择)。如果我的直觉是正确的......那么这不是MPI的工作方式。
另一方面,如果你的算法是正确的(完全不清楚),它是不平衡的,因为不同的MPI任务将执行不同的迭代次数。因此,您的代码将以最慢的代码执行,即my_rank == 0的任务。
我的负面评论的原因是你说“这是我第一次写一个MPI程序”而你之前只尝试过“hello world”。我强烈建议你尝试一些更典型的例子:分布式总和,幽灵单元......然后当你更好地了解它如何与简单的测试用例一起工作时,你继续开始解决你自己的问题。
您应该开始在这里发布一个工作代码,如果实际问题太大而无法从您的实际问题中提取。请参阅here,特别是here:您会看到尝试解释它,您甚至会在发布之前澄清自己。
MPI_Bcast() - 帖子的标题 - 看起来非常正确:你应该开始打印它们以开始调试代码,如果你不想从并行调试器开始(那不会根本不是一个坏主意... ...但似乎你还没有尝试过。我会在第一个MPI_Bcast()之后开始添加这一行:
cout << my_rank << ": azimuth[0]="<< azimuth[0] << endl;
希望我的批评更清楚。