Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
convert options to sphinx
[simgrid.git] / docs / source / tuto_smpi / roundtrip.c
1 #include <mpi.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 #define N (1024 * 1024 * 1)
6
7 int main(int argc, char* argv[])
8 {
9   int size, rank;
10   struct timeval start, end;
11   char hostname[256];
12   int hostname_len;
13
14   MPI_Init(&argc, &argv);
15
16   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
17   MPI_Comm_size(MPI_COMM_WORLD, &size);
18   MPI_Get_processor_name(hostname, &hostname_len);
19
20   // Allocate a 1 MiB buffer
21   char* buffer = malloc(sizeof(char) * N);
22
23   // Communicate along the ring
24   if (rank == 0) {
25     gettimeofday(&start, NULL);
26     printf("Rank %d (running on '%s'): sending the message rank %d\n", rank, hostname, 1);
27     MPI_Send(buffer, N, MPI_BYTE, 1, 1, MPI_COMM_WORLD);
28     MPI_Recv(buffer, N, MPI_BYTE, size - 1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
29     printf("Rank %d (running on '%s'): received the message from rank %d\n", rank, hostname, size - 1);
30     gettimeofday(&end, NULL);
31     printf("%f\n", (end.tv_sec * 1000000.0 + end.tv_usec - start.tv_sec * 1000000.0 - start.tv_usec) / 1000000.0);
32
33   } else {
34     MPI_Recv(buffer, N, MPI_BYTE, rank - 1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
35     printf("Rank %d (running on '%s'): receive the message and sending it to rank %d\n", rank, hostname,
36            (rank + 1) % size);
37     MPI_Send(buffer, N, MPI_BYTE, (rank + 1) % size, 1, MPI_COMM_WORLD);
38   }
39
40   MPI_Finalize();
41   return 0;
42 }