Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'mc' into mc++
[simgrid.git] / examples / smpi / 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
28   int size, rank;
29   int N;
30   struct timeval *start_time = NULL, *stop_time = NULL;
31   double seconds = 0;
32   int i, j;
33   char *buffer;
34   int check;
35
36   srandom(RAND_SEED);
37
38   MPI_Init(&argc, &argv);
39
40   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
41   MPI_Comm_size(MPI_COMM_WORLD, &size);
42
43   if (0 == rank) {
44     start_time = (struct timeval *) malloc(sizeof(struct timeval));
45     stop_time = (struct timeval *) malloc(sizeof(struct timeval));
46   }
47
48   for (N = N_START; N <= N_STOP; N = N_NEXT) {
49
50     buffer = malloc(sizeof(char) * N);
51
52     if (0 == rank) {
53       for (j = 0; j < N; j++) {
54         buffer[j] = (char) (random() % 256);
55       }
56       if (-1 == gettimeofday(start_time, NULL)) {
57         printf("couldn't set start_time on node 0!\n");
58         MPI_Abort(MPI_COMM_WORLD, GETTIMEOFDAY_ERROR);
59         exit(EXIT_FAILURE);
60       }
61     }
62
63     for (i = 0; i < ITER; i++) {
64       MPI_Bcast(buffer, N, MPI_BYTE, 0, MPI_COMM_WORLD);
65       if (0 == rank) {
66         for (j = 1; j < size; j++) {
67           MPI_Recv(&check, 1, MPI_INT, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD,
68                    MPI_STATUS_IGNORE);
69         }
70       } else {
71         MPI_Send(&rank, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
72       }
73     }
74
75     if (0 == rank) {
76       if (-1 == gettimeofday(stop_time, NULL)) {
77         printf("couldn't set start_time on node 0!\n");
78         MPI_Abort(MPI_COMM_WORLD, GETTIMEOFDAY_ERROR);
79         exit(EXIT_FAILURE);
80       }
81       seconds =
82           (double) (stop_time->tv_sec - start_time->tv_sec) +
83           (double) (stop_time->tv_usec -
84                     start_time->tv_usec) / ONE_MILLION;
85     }
86
87     free(buffer);
88
89     if (0 == rank) {
90       printf("N: %10d, iter: %d, time: %10f s, avg rate: %12f Mbps\n", N,
91              ITER, seconds,
92              ((double) N * ITER * 8) / (1024.0 * 1024.0 * seconds));
93     }
94
95   }
96
97   if (0 == rank) {
98     free(start_time);
99     free(stop_time);
100   }
101
102   MPI_Finalize();
103
104   return 0;
105 }