这个 C++ 程序中的 MPI_Bcast() 是做什么用的?
What is the MPI_Bcast() for in this C++ program?
我开始学习 MPI 并从 Russian IT blog Habrahabr:
获取了这个教程代码示例
#include <mpi.h>
#include <iostream>
#include <windows.h>
using namespace std;
double Fact(int n)
{
if (n==0) return 1;
else return n*Fact(n-1);
}
int main(int argc, char *argv[])
{
int n;
int myid;
int numprocs;
int i;
int rc;
long double drob,drobSum=0,Result, sum;
double startwtime = 0.0;
double endwtime;
n = atoi(argv[1]);
if (rc= MPI_Init(&argc, &argv)) {
cout << "Launch error" << endl;
MPI_Abort(MPI_COMM_WORLD, rc);
}
MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
if (myid == 0) {
startwtime = MPI_Wtime();
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
for (i = myid; i <= n; i += numprocs)
{
drob = 1/Fact(i);
drobSum += drob;
}
MPI_Reduce(&drobSum, &Result, 1, MPI_LONG_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
cout.precision(20);
if (myid == 0)
{
cout << Result << endl;
endwtime = MPI_Wtime();
cout << (endwtime-startwtime)*1000 << endl;
}
MPI_Finalize();
return 0;
}
我的问题是他们为什么需要
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
在那里,如果 n
值在所有进程中设置
n = atoi(argv[1]);
无论如何。
这只是一个错误还是有任何目的?我测试了代码,没有它也能正常工作。
我想也许广播暗示了一些过程工作流障碍,用于正确计算时间测量或其他东西。
我还认为它可能在那里,因为 n
初始化在 MPI_Init()
调用之前进行。
如果我将 n = atoi(argv[1]);
放在 MPI_Init()
之后,我是否需要在此代码中使用 MPI_Bcast()
?
MPI_Init()
之前的任何内容都是 undefined behavior in MPI。如果您不想广播命令行参数,那么您应该在 MPI_Init(&argc, &argv)
之后使用 argv
和 argc
,因为这样它们将保证对所有任务可用。
代码工作正常,因为许多 MPI 实现在初始化之前使 argv
和 argc
可用,但您不应依赖此行为。
我开始学习 MPI 并从 Russian IT blog Habrahabr:
获取了这个教程代码示例#include <mpi.h>
#include <iostream>
#include <windows.h>
using namespace std;
double Fact(int n)
{
if (n==0) return 1;
else return n*Fact(n-1);
}
int main(int argc, char *argv[])
{
int n;
int myid;
int numprocs;
int i;
int rc;
long double drob,drobSum=0,Result, sum;
double startwtime = 0.0;
double endwtime;
n = atoi(argv[1]);
if (rc= MPI_Init(&argc, &argv)) {
cout << "Launch error" << endl;
MPI_Abort(MPI_COMM_WORLD, rc);
}
MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
if (myid == 0) {
startwtime = MPI_Wtime();
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
for (i = myid; i <= n; i += numprocs)
{
drob = 1/Fact(i);
drobSum += drob;
}
MPI_Reduce(&drobSum, &Result, 1, MPI_LONG_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
cout.precision(20);
if (myid == 0)
{
cout << Result << endl;
endwtime = MPI_Wtime();
cout << (endwtime-startwtime)*1000 << endl;
}
MPI_Finalize();
return 0;
}
我的问题是他们为什么需要
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
在那里,如果 n
值在所有进程中设置
n = atoi(argv[1]);
无论如何。
这只是一个错误还是有任何目的?我测试了代码,没有它也能正常工作。
我想也许广播暗示了一些过程工作流障碍,用于正确计算时间测量或其他东西。
我还认为它可能在那里,因为 n
初始化在 MPI_Init()
调用之前进行。
如果我将 n = atoi(argv[1]);
放在 MPI_Init()
之后,我是否需要在此代码中使用 MPI_Bcast()
?
MPI_Init()
之前的任何内容都是 undefined behavior in MPI。如果您不想广播命令行参数,那么您应该在 MPI_Init(&argc, &argv)
之后使用 argv
和 argc
,因为这样它们将保证对所有任务可用。
代码工作正常,因为许多 MPI 实现在初始化之前使 argv
和 argc
可用,但您不应依赖此行为。