Message Passing Interface (MPI) : MPI_Comm_size example

by

in

This post talks about MPI_Comm_size function in MPI. MPI_Comm_size is a function in the Message Passing Interface (MPI) used to determine the total number of processes in a communicator.

Syntax for MPI_Comm_size

int MPI_Comm_size( MPI_Comm comm, int *size )

Input Parameters

  • comm : communicator (for example : MPI_COMM_WORLD)

Output Parameter

  • size : number of processes 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