Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
exclude the NAS from sonar. Not my business.
[simgrid.git] / examples / smpi / bcbench / bcbench.c
1 /* Copyright (c) 2009-2010, 2012-2014. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <mpi.h>
10
11 #ifdef _WIN32
12   #define srandom srand
13   #define random rand
14 #endif
15
16 #define GETTIMEOFDAY_ERROR 1
17
18 #define N_START 1
19 #define N_STOP  1024*1024
20 #define N_NEXT  (N*2)
21 #define ITER    100
22 #define ONE_MILLION 1000000.0
23 #define RAND_SEED 842270
24
25 int main(int argc, char *argv[])
26 {
27   int size, rank;
28   struct timeval *start_time = NULL, *stop_time = NULL;
29   double seconds = 0;
30   char *buffer;
31   int check;
32
33   srandom(RAND_SEED);
34
35   MPI_Init(&argc, &argv);
36
37   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
38   MPI_Comm_size(MPI_COMM_WORLD, &size);
39
40   if (0 == rank) {
41     start_time = (struct timeval *) malloc(sizeof(struct timeval));
42     stop_time = (struct timeval *) malloc(sizeof(struct timeval));
43   }
44
45   for (int N = N_START; N <= N_STOP; N = N_NEXT) {
46     buffer = malloc(sizeof(char) * N);
47
48     if (0 == rank) {
49       for (int j = 0; j < N; j++) {
50         buffer[j] = (char) (random() % 256);
51       }
52       if (-1 == gettimeofday(start_time, NULL)) {
53         printf("couldn't set start_time on node 0!\n");
54         MPI_Abort(MPI_COMM_WORLD, GETTIMEOFDAY_ERROR);
55         exit(EXIT_FAILURE);
56       }
57     }
58
59     for (int i = 0; i < ITER; i++) {
60       MPI_Bcast(buffer, N, MPI_BYTE, 0, MPI_COMM_WORLD);
61       if (0 == rank) {
62         for (int j = 1; j < size; j++) {
63           MPI_Recv(&check, 1, MPI_INT, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
64         }
65       } else {
66         MPI_Send(&rank, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
67       }
68     }
69
70     if (0 == rank) {
71       if (-1 == gettimeofday(stop_time, NULL)) {
72         printf("couldn't set start_time on node 0!\n");
73         MPI_Abort(MPI_COMM_WORLD, GETTIMEOFDAY_ERROR);
74         exit(EXIT_FAILURE);
75       }
76       seconds = (double) (stop_time->tv_sec - start_time->tv_sec) +
77                 (double) (stop_time->tv_usec - start_time->tv_usec) / ONE_MILLION;
78     }
79
80     free(buffer);
81
82     if (0 == rank) {
83       printf("N: %10d, iter: %d, time: %10f s, avg rate: %12f Mbps\n", N, ITER, seconds,
84              ((double) N * ITER * 8) / (1024.0 * 1024.0 * seconds));
85     }
86   }
87
88   if (0 == rank) {
89     free(start_time);
90     free(stop_time);
91   }
92
93   MPI_Finalize();
94
95   return 0;
96 }