Message Passing Interface (MPI) : MPI_Reduce example

by

in

This post talks about Reduction operation in MPI using MPI_Reduce. In reduction operation, each process contributes its local data, and these values are aggregated according to the specified operation such as summation, finding the maximum, or custom-defined functions.

Syntax for MPI_Reduce

int MPI_Reduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm)

Input Parameters

  • sendbuf : Pointer to the data/array to be sent (for example : int *mydata)
  • count : number of elements/values to be sent (for example : 10)
  • datatype : data type of elements/values to be sent (for example : MPI_INT)
  • op : reduction operation to be performed (for example – MPI_SUM)
  • root : rank of root process (for example : 0)
  • comm : communicator (for example : MPI_COMM_WORLD)

Output Parameters

  • recvbuf : Pointer to the data/array to be received (for example : int *myarr)

Example code –

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

int main(int argc, char **argv)
{
	int myid, size;
	int sum;
	
	sum = 100;
	 
	MPI_Init(&argc,&argv);
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &myid);

        MPI_Reduce(&myid, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);	
	
	if(myid==0)
	{
	    printf("\n sum = %d\n",sum);
	}
	
        MPI_Finalize();	
}	

To compile this code, use following command –

mpicc mpi_reduce.c

To execute this code, run following command –

mpiexec -n 4 ./a.out

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

 sum = 6

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