#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"

#define MSG_SIZE 1024
#define MAX_SENDS 5000

#define MIN(a,b) ((a)<(b)? (a):(b))

int main (int argc, char * argv[])
{
  int size;
  int rank;
  int i;
  int how_many_times;
  char * buffer;
  double time_start, time_stop;
  MPI_Status status;

  MPI_Init (&argc, &argv);
  MPI_Comm_rank (MPI_COMM_WORLD, &rank);
  MPI_Comm_size (MPI_COMM_WORLD, &size);

  if (size != 2)
    {
      fprintf (stderr, "Needs to be run with 2 processes\n");
      MPI_Abort (MPI_COMM_WORLD, -1);
    }

  /*
   * Allocate the memory
   */
  buffer = malloc (MSG_SIZE);
  if (buffer == NULL)
    {
      fprintf (stderr, "Could not allocate memory\n");
      MPI_Abort (MPI_COMM_WORLD, -1);
    }


  /*
   * Send at least 1000 Times 
   * But at max 40 MB.
   */
  how_many_times = MIN(((40*1024)/(MSG_SIZE/1024))+1, MAX_SENDS);

  time_start = MPI_Wtime(); 

  if (rank == 0)
    for (i = 0; i < how_many_times; i++)
        MPI_Send (buffer, MSG_SIZE, MPI_BYTE, 1, 4711, MPI_COMM_WORLD);
  else
    for (i = 0; i < how_many_times; i++)
        MPI_Recv (buffer, MSG_SIZE, MPI_BYTE, 0, 4711, MPI_COMM_WORLD, &status);

  time_stop = MPI_Wtime(); 

  if (rank == 0)
    printf ("MSG_SIZE:%d how_many:%d MegaByte/sec:%f\n",
            MSG_SIZE, how_many_times,
            ((float)MSG_SIZE/1024.0 * how_many_times)/
             (1024.0*(time_stop-time_start)) ); 

  MPI_Finalize ();
  return 0;
}

