/* 02_pingpong.c - measure point-to-point latency and bandwidth between two ranks.
 * Build: mpicc -O2 -o 02_pingpong 02_pingpong.c
 * Run:   mpirun -np 2 ./02_pingpong
 * Tip:   run the two ranks on different nodes to measure the network instead of shared memory.
 */
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

#define REPS 200

int main(int argc, char **argv)
{
    int rank, size;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    if (size != 2) {
        if (rank == 0) fprintf(stderr, "Run with exactly 2 processes.\n");
        MPI_Abort(MPI_COMM_WORLD, 1);
    }

    const int max_bytes = 1 << 22;                 /* 4 MiB */
    char *buf = malloc(max_bytes);
    for (int i = 0; i < max_bytes; i++) buf[i] = (char)i;

    if (rank == 0) printf("%10s %14s %14s\n", "bytes", "latency [us]", "bandwidth [MB/s]");

    for (int bytes = 1; bytes <= max_bytes; bytes *= 4) {
        MPI_Barrier(MPI_COMM_WORLD);
        double t0 = MPI_Wtime();
        for (int r = 0; r < REPS; r++) {
            if (rank == 0) {
                MPI_Send(buf, bytes, MPI_CHAR, 1, 0, MPI_COMM_WORLD);
                MPI_Recv(buf, bytes, MPI_CHAR, 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            } else {
                MPI_Recv(buf, bytes, MPI_CHAR, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
                MPI_Send(buf, bytes, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
            }
        }
        double one_way = (MPI_Wtime() - t0) / (2.0 * REPS);   /* seconds per message */
        if (rank == 0)
            printf("%10d %14.2f %14.1f\n", bytes, one_way * 1e6, bytes / one_way / 1e6);
    }

    free(buf);
    MPI_Finalize();
    return 0;
}
