Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2022.
[simgrid.git] / docs / source / tuto_smpi / roundtrip.c
1 /* Copyright (c) 2018-2022. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <mpi.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9
10 #define N (1024 * 1024 * 1)
11
12 int main(int argc, char* argv[])
13 {
14   int size, rank;
15   struct timeval start, end;
16   char hostname[256];
17   int hostname_len;
18
19   MPI_Init(&argc, &argv);
20
21   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
22   MPI_Comm_size(MPI_COMM_WORLD, &size);
23   MPI_Get_processor_name(hostname, &hostname_len);
24
25   // Allocate a 1 MiB buffer
26   char* buffer = malloc(sizeof(char) * N);
27
28   // Communicate along the ring
29   if (rank == 0) {
30     gettimeofday(&start, NULL);
31     printf("Rank %d (running on '%s'): sending the message rank %d\n", rank, hostname, 1);
32     MPI_Send(buffer, N, MPI_BYTE, 1, 1, MPI_COMM_WORLD);
33     MPI_Recv(buffer, N, MPI_BYTE, size - 1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
34     printf("Rank %d (running on '%s'): received the message from rank %d\n", rank, hostname, size - 1);
35     gettimeofday(&end, NULL);
36     printf("%f\n", (end.tv_sec * 1000000.0 + end.tv_usec - start.tv_sec * 1000000.0 - start.tv_usec) / 1000000.0);
37
38   } else {
39     MPI_Recv(buffer, N, MPI_BYTE, rank - 1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
40     printf("Rank %d (running on '%s'): receive the message and sending it to rank %d\n", rank, hostname,
41            (rank + 1) % size);
42     MPI_Send(buffer, N, MPI_BYTE, (rank + 1) % size, 1, MPI_COMM_WORLD);
43   }
44
45   MPI_Finalize();
46   return 0;
47 }