直观印象--简单的MPI程序实例
一个简单的MPI程序的例子(FORTRAN)
!simple.f
program main
include 'mpif.h'
character*(MPI_MAX_PROCESSOR_NAME) processor_name
integer myid, numprocs, namelen, rc, ierr
! MPI initialization phase
call MPI_INIT( ierr )
call MPI_COMM_RANK( MPI_COMM_WORLD, myid, ierr )
call MPI_COMM_SIZE( MPI_COMM_WORLD, numprocs, ierr )
call MPI_GET_PROCESSOR_NAME( processor_name, namelen, ierr )
! MPI working phase
print *, "This is Process", myid, "of",numprocs,"on",
processor_name
! MPI finalization phase
call MPI_FINALIZE( rc )
end
用mpif90命令将这个程序编译:
mpif90 -o simple simple.f
然后用mpirun来运行这个程序(假定已经设置好了配置文件)。
mpirun -np 4 simple
为这个程序指定四个工作进程,如果这个程序在一个集群系统的某台计算机cluster1上运行,它的输出结果(可能)如下:
This is Process 0 of 4 on cluster1
This is Process 2 of 4 on cluster1
This is Process 1 of 4 on cluster1
This is Process 3 of 4 on cluster1
如果这个程序在一个集群系统的四台不同计算机cluster1-cluster4上运行,它的输出结果(可能)如下:
This is Process 0 of 4 on cluster1
This is Process 2 of 4 on cluster3
This is Process 1 of 4 on cluster2
This is Process 3 of 4 on cluster4
这个程序的C语言版本如下:
// simple.c
#include "mpi.h"
#inlucde <stdio.h>
#include <math.h>
int main( int argc, char **argv)
{
int myid, numprocs;
int namelen;
char processor_name[ MPI_MAX_PROCESSOR_NAME ];
// MPI Initialization phase
MPI_Init( & argc, &argv );
MPI_Comm_rank( MPI_COMM_WORLD, &myid );
MPI_Comm_size( MPI_COMM_WORLD, &numprocs );
MPI_Get_processor_name( processor_name, &namelen );
// The working phase
Printf("This is Process %d of %d on %s\n", myid, numprocs,
processor_name );
// MPI Finalization phase
MPI_Finalize( );
}
用mpicc命令将这个程序编译:
mpicc -o simple simple.c
然后用mpirun来运行这个程序(假定已经设置好了配置文件)。
mpirun -np 4 simple
这个程序的运行结果和上面的Fortran程序相似。本节中将采用c语言对MPI的编程规范进行说明。 这两个程序的运行过程可以用下面的图来表示:
|