Message Passing Interface (MPI) : MPI_Comm_rank example

by

in

This post talks about MPI_Comm_rank function in MPI. MPI_Comm_rank function in the Message Passing Interface (MPI) is used to determine the rank (or unique ID) of a process within a communicator. Each process in an MPI program has a unique rank, which is an integer ranging from 0 to size-1 (where size is the total number of processes in the communicator).

Syntax for MPI_Comm_rank

int MPI_Comm_rank( MPI_Comm comm, int *rank )

Input Parameters

  • comm : communicator (for example : MPI_COMM_WORLD)

Output Parameter

  • rank : rank of the calling process in the group of comm (integer)

Example code –

#include"stdio.h"
#include"mpi.h"

int main(int argc, char **argv)
{
int myid, size;

//Initialize MPI environment
MPI_Init(&argc,&argv);

//Get total number of processes
MPI_Comm_size(MPI_COMM_WORLD, &size);

//Get my unique ID among all processes
MPI_Comm_rank(MPI_COMM_WORLD, &myid);

printf("Hello World from %d out of %d.\n",myid, size);

//End MPI environment
MPI_Finalize();
}

To compile this code, use following command –

mpicc hello_world.c

To execute this code, run following command –

mpiexec -n 4 ./a.out

Output of this code will be something similar to the following –


Hello World from 0 out of 4.
Hello World from 1 out of 4.
Hello World from 2 out of 4.
Hello World from 3 out of 4.

To know more about MPI, visit our dedicated page for MPI here.

If you are new to Parallel Programming / HPC, visit our dedicated page for beginners.

References :


Mandar Gurav Avatar

Mandar Gurav

Parallel Programmer, Trainer and Mentor


If you are new to Parallel Programming you can start here.



Beginner CUDA Fortran Hello World Message Passing Interface MPI Nvidia Nsight Systems NVPROF OpenACC OpenACC Fortran OpenMP PGI Fortran Compiler Profiling Vector Addition


Popular Categories