Logo AND Algorithmique Numérique Distribuée

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