Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
9a733c96693b52859eb4a4e6a2723349ae69cc08
[simgrid.git] / examples / smpi / energy / energy.c
1 /* Copyright (c) 2013-2021. 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 #include <smpi/smpi.h>
11
12 #include <simgrid/host.h>
13 #include <simgrid/plugins/energy.h>
14
15 int main(int argc, char *argv[])
16 {
17   int rank;
18   unsigned long i;
19   char buf[1024];
20
21   int err = MPI_Init(&argc, &argv);
22   if (err != MPI_SUCCESS) {
23     fprintf(stderr, "MPI_init failed: %d\n", err);
24     exit(EXIT_FAILURE);
25   }
26
27   err = MPI_Comm_rank(MPI_COMM_WORLD, &rank);   /* Get id of this process */
28   if (err != MPI_SUCCESS) {
29     fprintf(stderr, "MPI_Comm_rank failed: %d", err);
30     MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
31     exit(EXIT_FAILURE);
32   }
33
34   unsigned long pstates = sg_host_get_nb_pstates(sg_host_self());
35
36   char *s = buf;
37   size_t sz = sizeof buf;
38   size_t x  = snprintf(s, sz, "[%.6f] [rank %d] Pstates: %lu; Powers: %.0f", MPI_Wtime(), rank, pstates,
39                       sg_host_get_pstate_speed(sg_host_self(), 0));
40   if (x < sz) {
41     s += x;
42     sz -= x;
43   } else
44     sz = 0;
45   for (i = 1; i < pstates; i++) {
46     x = snprintf(s, sz, ", %.0f", sg_host_get_pstate_speed(sg_host_self(), i));
47     if (x < sz) {
48       s += x;
49       sz -= x;
50     } else
51       sz = 0;
52   }
53   fprintf(stderr, "%s%s\n", buf, (sz ? "" : " [...]"));
54
55   for (i = 0; i < pstates; i++) {
56     sg_host_set_pstate(sg_host_self(), i);
57     fprintf(stderr, "[%.6f] [rank %d] Current pstate: %lu; Current power: %.0f\n", MPI_Wtime(), rank, i,
58             sg_host_get_speed(sg_host_self()));
59
60     SMPI_SAMPLE_FLOPS(1e9) {
61       /* imagine here some code running for 1e9 flops... */
62     }
63
64     fprintf(stderr, "[%.6f] [rank %d] Energy consumed: %g Joules.\n",
65             MPI_Wtime(), rank,  sg_host_get_consumed_energy(sg_host_self()));
66   }
67
68   err = MPI_Finalize();
69   if (err != MPI_SUCCESS) {
70     fprintf(stderr, "MPI_Finalize failed: %d\n", err);
71     MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
72     exit(EXIT_FAILURE);
73   }
74
75   return EXIT_SUCCESS;
76 }