具有串行和并行编译选项的MPI程序 我编写了一个MPI程序,可以与C++并行。我想让它成为可选的并行或串行编译。以下面的hello world计划为例,实现这一目标的常见做法是什么?我看到一些软件使用选项--serial/--parallel编译,但不确定具体是如何完成的

具有串行和并行编译选项的MPI程序 我编写了一个MPI程序,可以与C++并行。我想让它成为可选的并行或串行编译。以下面的hello world计划为例,实现这一目标的常见做法是什么?我看到一些软件使用选项--serial/--parallel编译,但不确定具体是如何完成的,mpi,Mpi,MPI版本: #include <mpi.h> #include <stdio.h> int main(int argc, char** argv) { MPI_Init(&argc, &argv); int numprocs; int procid; MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &

MPI版本:

#include <mpi.h>
#include <stdio.h>

int main(int argc, char** argv) {

    MPI_Init(&argc, &argv);

    int numprocs;
    int procid;
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &procid);

    printf("Hello world from process %d \n", procid);

    MPI_Finalize();
}
#包括
#包括
int main(int argc,字符**argv){
MPI_Init(&argc,&argv);
国际货币基金组织;
int-procid;
MPI通信大小(MPI通信世界和numprocs);
MPI通信等级(MPI通信世界和procid);
printf(“来自进程%d\n的Hello world”,procid);
MPI_Finalize();
}
序列版本:

#include <stdio.h>

int main(int argc, char** argv) {
    num = stoi(argv[1]);
    for (int i = 0; i < num; i++){
        printf("Hello world from process %d \n", num);
    }
}
#包括
int main(int argc,字符**argv){
num=stoi(argv[1]);
for(int i=0;i
您的问题分为两个级别:

  • 首先,您可能希望编译相同的源代码,使用和不使用MPI,生成两个不同的程序——一个并行程序,一个串行程序
  • 或者,您可能希望编译一个程序(使用MPI),但使用命令行选项指定该程序是以串行模式还是以并行模式执行
下面的代码将两者结合起来

如果第一个命令行参数为“-parallel”,则程序将从MPI初始化例程开始,并以MPI终结例程结束

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
    int iproc = 0;
    int nproc = 1;
    int par   = (strcmp(argv[1], "-parallel") == 0);
    int nwork = atoi(argv[2]);

    if (par) parallel_init(&argc, &argv, &iproc, &nproc);

    for (int i = 0; i < nwork; i++)
    {
        if (i % nproc == iproc)
        {
            printf("Running task %d by rank %d\n", i, iproc);
            /* ... etc ... */
        }
    }

    if (par) parallel_final();

    return 0;
}
例如:


嗨,雅各布,非常感谢你。您提供的第二个示例正是我想要的。请记住,MPI程序通常可以在没有
mpirun
(也称为单例模式)的情况下按原样运行,因此除非您计划在MPI运行时不可用的节点上执行“串行”版本,否则最简单的选择可能是只构建并行版本。另一个选项是使用一些MPI存根库,因此构建串行版本所需的全部工作就是更改makefile(读取无需修改源代码)。
#ifndef NOMPI
#include <mpi.h>
#endif

void parallel_init (int *pargc, char **pargv[], int *piproc, int *pnproc)
{
#ifdef NOMPI
    *piproc = 0;
    *pnproc = 1;
#else
    MPI_Init(pargc, pargv);
    MPI_Comm_size(MPI_COMM_WORLD, pnproc);
    MPI_Comm_rank(MPI_COMM_WORLD, piproc);
#endif
}

void parallel_final ()
{
#ifndef NOMPI
    MPI_Finalize();
#endif
}
> mpicc main.c 
> ./a.out -serial 4
Running task 0 by rank 0
Running task 1 by rank 0
Running task 2 by rank 0
Running task 3 by rank 0
> mpiexec -n 2 ./a.out -parallel 4
Running task 0 by rank 0
Running task 2 by rank 0
Running task 1 by rank 1
Running task 3 by rank 1