Logo AND Algorithmique Numérique Distribuée

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