From e9f667cf05876aa44a180d653f6f46d283400524 Mon Sep 17 00:00:00 2001 From: Tuomas Rossi Date: Wed, 26 Jun 2024 20:38:54 +0300 Subject: [PATCH] Add demo for reductions --- mpi/demos/reduce.c | 25 +++++++++++++++++++++++++ mpi/docs/05-collective-reductions.md | 10 ++++++++++ 2 files changed, 35 insertions(+) create mode 100644 mpi/demos/reduce.c diff --git a/mpi/demos/reduce.c b/mpi/demos/reduce.c new file mode 100644 index 000000000..9a15d175c --- /dev/null +++ b/mpi/demos/reduce.c @@ -0,0 +1,25 @@ +#include +#include + +int main(int argc, char *argv[]) +{ + int size, rank; + MPI_Init(&argc, &argv); + MPI_Comm_size(MPI_COMM_WORLD, &size); + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + + printf("Hello from rank %d of %d\n", rank, size); + + double data[2] = {1. * rank, -1. * rank}; + printf("Rank %d data is (%.1f, %.1f)\n", rank, data[0], data[1]); + + double sum_of_data[2]; + MPI_Reduce(data, sum_of_data, 2, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); +// MPI_Allreduce(data, sum_of_data, 2, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); +// MPI_Allreduce(MPI_IN_PLACE, data, 2, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); + + printf("Rank %d data after reduce is (%.1f, %.1f)\n", rank, data[0], data[1]); + printf("Rank %d sum_of_data after reduce is (%.1f, %.1f)\n", rank, sum_of_data[0], sum_of_data[1]); + + MPI_Finalize(); +} diff --git a/mpi/docs/05-collective-reductions.md b/mpi/docs/05-collective-reductions.md index 5ea03794a..6e98d2f72 100644 --- a/mpi/docs/05-collective-reductions.md +++ b/mpi/docs/05-collective-reductions.md @@ -45,6 +45,10 @@ lang: en MPI_Reduce(`sendbuf`{.input}, `recvbuf`{.output}, `count`{.input}, `datatype`{.input}, `op`{.input}, `root`{.input}, `comm`{.input}) : Combines values to the root process from all processes of the group +

+- Demo: `reduce.c` + + # Global reduction MPI_Allreduce(`sendbuf`{.input}, `recvbuf`{.output}, `count`{.input}, `datatype`{.input}, `op`{.input}, `comm`{.input}) @@ -53,6 +57,9 @@ MPI_Allreduce(`sendbuf`{.input}, `recvbuf`{.output}, `count`{.input}, `datatype`

- Similar to `MPI_Reduce` + `MPI_Bcast` but more efficient +

+- Demo: `reduce.c` + # Allreduce example: parallel dot product @@ -93,6 +100,9 @@ call mpi_allreduce(rloc, r, 1, MPI_REAL, & `call mpi_allreduce(a, a, n, mpi_real,...` - One should employ `MPI_IN_PLACE` for this purpose - Replacing the send buffer with the `MPI_IN_PLACE` clause informs MPI that the buffers are the same +

+- Demo: `reduce.c` + # Summary