Logo AND Algorithmique Numérique Distribuée

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