debug.c 18.9 KB
Newer Older
1
2
/*******************************************************************************
 * This file is part of SWIFT.
Peter W. Draper's avatar
Peter W. Draper committed
3
4
5
6
 * Copyright (c) 2013- 2015:
 *                    Matthieu Schaller (matthieu.schaller@durham.ac.uk),
 *                    Pedro Gonnet (pedro.gonnet@durham.ac.uk),
 *                    Peter W. Draper (p.w.draper@durham.ac.uk).
7
 *
8
9
10
11
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
12
 *
13
14
15
16
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
17
 *
18
19
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
 *
21
22
 ******************************************************************************/

23
/* Config parameters. */
24
25
26

/* This object's header. */
#include "debug.h"
27
28

/* Some standard headers. */
29
#include <float.h>
30
#include <stdio.h>
31
#include <unistd.h>
32

33
/* Local includes. */
34
#include "active.h"
35
36
#include "cell.h"
#include "engine.h"
37
#include "hydro.h"
38
#include "inline.h"
39
#include "part.h"
40
#include "space.h"
41

42
/* Import the right hydro definition */
43
44
45
#if defined(DEBUG_INTERACTIONS_SPH)
#include "./hydro/DebugInteractions/hydro_debug.h"
#elif defined(MINIMAL_SPH)
46
47
#include "./hydro/Minimal/hydro_debug.h"
#elif defined(GADGET2_SPH)
48
#include "./hydro/Gadget2/hydro_debug.h"
49
50
#elif defined(HOPKINS_PE_SPH)
#include "./hydro/PressureEntropy/hydro_debug.h"
51
#elif defined(DEFAULT_SPH)
52
#include "./hydro/Default/hydro_debug.h"
53
54
#elif defined(GIZMO_SPH)
#include "./hydro/Gizmo/hydro_debug.h"
55
#elif defined(SHADOWFAX_SPH)
56
#include "./hydro/Shadowswift/hydro_debug.h"
57
58
#else
#error "Invalid choice of SPH variant"
59
60
#endif

61
62
#include "./gravity/Default/gravity_debug.h"

63
/**
64
65
66
 * @brief Looks for the particle with the given id and prints its information to
 *the standard output.
 *
67
 * @param parts The array of particles.
Matthieu Schaller's avatar
Matthieu Schaller committed
68
 * @param xparts The array of particle extended data.
69
70
71
72
73
 * @param id The id too look for.
 * @param N The size of the array of particles.
 *
 * (Should be used for debugging only as it runs in O(N).)
 */
74
void printParticle(const struct part *parts, const struct xpart *xparts,
Matthieu Schaller's avatar
Style    
Matthieu Schaller committed
75
                   long long int id, size_t N) {
76

77
  int found = 0;
78
79

  /* Look for the particle. */
80
  for (size_t i = 0; i < N; i++)
81
    if (parts[i].id == id) {
82
      printf("## Particle[%zu]:\n id=%lld ", i, parts[i].id);
83
      hydro_debug_particle(&parts[i], &xparts[i]);
84
      found = 1;
85
      break;
86
87
    }

88
89
  if (!found) printf("## Particles[???] id=%lld not found\n", id);
}
90

91
92
93
94
95
96
/**
 * @brief Looks for the g-particle with the given id and prints its information
 * to
 * the standard output.
 *
 * @param gparts The array of g-particles.
Matthieu Schaller's avatar
Matthieu Schaller committed
97
 * @param parts The array of particles.
98
99
100
101
102
 * @param id The id too look for.
 * @param N The size of the array of g-particles.
 *
 * (Should be used for debugging only as it runs in O(N).)
 */
Matthieu Schaller's avatar
Style    
Matthieu Schaller committed
103
104
void printgParticle(const struct gpart *gparts, const struct part *parts,
                    long long int id, size_t N) {
105

106
  int found = 0;
107
108

  /* Look for the particle. */
109
  for (size_t i = 0; i < N; i++)
110
    if (gparts[i].id_or_neg_offset == id) {
111
      printf("## gParticle[%zu] (DM) :\n id=%lld", i, id);
112
113
114
      gravity_debug_particle(&gparts[i]);
      found = 1;
      break;
115
116
    } else if (gparts[i].id_or_neg_offset < 0 &&
               parts[-gparts[i].id_or_neg_offset].id == id) {
117
      printf("## gParticle[%zu] (hydro) :\n id=%lld", i, id);
118
      gravity_debug_particle(&gparts[i]);
119
      found = 1;
120
      break;
121
    }
122

123
124
  if (!found) printf("## Particles[???] id=%lld not found\n", id);
}
125

Pedro Gonnet's avatar
Pedro Gonnet committed
126
/**
127
 * @brief Prints the details of a given particle to stdout
128
 *
129
 * @param p The particle to print
130
 * @param xp The extended data ot the particle to print
Pedro Gonnet's avatar
Pedro Gonnet committed
131
 */
132
void printParticle_single(const struct part *p, const struct xpart *xp) {
133

134
  printf("## Particle: id=%lld ", p->id);
135
  hydro_debug_particle(p, xp);
Matthieu Schaller's avatar
Matthieu Schaller committed
136
  printf("\n");
137
}
Peter W. Draper's avatar
Peter W. Draper committed
138

139
140
141
142
143
144
145
/**
 * @brief Prints the details of a given particle to stdout
 *
 * @param gp The g-particle to print
 */
void printgParticle_single(struct gpart *gp) {

146
  printf("## g-Particle: id=%lld ", gp->id_or_neg_offset);
147
148
  gravity_debug_particle(gp);
  printf("\n");
149
}
Peter W. Draper's avatar
Peter W. Draper committed
150

151
152
153
154
155
156
157
158
159
/**
 * @brief Check that the cells and particles of a space have consistent h_max
 *        values.
 *
 * @param s the space.
 * @result 1 or 0
 */
int checkSpacehmax(struct space *s) {

Peter W. Draper's avatar
Peter W. Draper committed
160
161
162
  /* Loop over local cells. */
  float cell_h_max = 0.0f;
  for (int k = 0; k < s->nr_cells; k++) {
163
164
165
    if (s->cells_top[k].nodeID == s->e->nodeID &&
        s->cells_top[k].h_max > cell_h_max) {
      cell_h_max = s->cells_top[k].h_max;
166
    }
Peter W. Draper's avatar
Peter W. Draper committed
167
  }
168

Peter W. Draper's avatar
Peter W. Draper committed
169
170
  /* Now all particles. */
  float part_h_max = 0.0f;
171
  for (size_t k = 0; k < s->nr_parts; k++) {
Peter W. Draper's avatar
Peter W. Draper committed
172
173
    if (s->parts[k].h > part_h_max) {
      part_h_max = s->parts[k].h;
174
    }
Peter W. Draper's avatar
Peter W. Draper committed
175
  }
176

Peter W. Draper's avatar
Peter W. Draper committed
177
  /*  If within some epsilon we are OK. */
178
  if (fabsf(cell_h_max - part_h_max) <= FLT_EPSILON) return 1;
179

Peter W. Draper's avatar
Peter W. Draper committed
180
181
  /* There is a problem. Hunt it down. */
  for (int k = 0; k < s->nr_cells; k++) {
182
183
184
    if (s->cells_top[k].nodeID == s->e->nodeID) {
      if (s->cells_top[k].h_max > part_h_max) {
        message("cell %d is inconsistent (%f > %f)", k, s->cells_top[k].h_max,
Peter W. Draper's avatar
Peter W. Draper committed
185
                part_h_max);
186
187
      }
    }
Peter W. Draper's avatar
Peter W. Draper committed
188
  }
189

190
  for (size_t k = 0; k < s->nr_parts; k++) {
Peter W. Draper's avatar
Peter W. Draper committed
191
192
193
    if (s->parts[k].h > cell_h_max) {
      message("part %lld is inconsistent (%f > %f)", s->parts[k].id,
              s->parts[k].h, cell_h_max);
194
    }
Peter W. Draper's avatar
Peter W. Draper committed
195
  }
196

Peter W. Draper's avatar
Peter W. Draper committed
197
  return 0;
198
199
}

200
201
/**
 * @brief Check if the h_max and dx_max values of a cell's hierarchy are
202
203
 * consistent with the particles. Also checks if particles are correctly
 * in a cell. Report verbosely if not.
204
205
206
207
208
209
210
211
212
213
214
 *
 * @param c the top cell of the hierarchy.
 * @param depth the recursion depth for use in messages. Set to 0 initially.
 * @result 1 or 0
 */
int checkCellhdxmax(const struct cell *c, int *depth) {

  *depth = *depth + 1;

  float h_max = 0.0f;
  float dx_max = 0.0f;
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
  int result = 1;

  const double loc_min[3] = {c->loc[0], c->loc[1], c->loc[2]};
  const double loc_max[3] = {c->loc[0] + c->width[0], c->loc[1] + c->width[1],
                             c->loc[2] + c->width[2]};

  const size_t nr_parts = c->count;
  struct part *parts = c->parts;
  struct xpart *xparts = c->xparts;
  for (size_t k = 0; k < nr_parts; k++) {

    struct part *const p = &parts[k];
    struct xpart *const xp = &xparts[k];

    if (p->x[0] < loc_min[0] || p->x[0] > loc_max[0] || p->x[1] < loc_min[1] ||
        p->x[1] > loc_max[1] || p->x[2] < loc_min[2] || p->x[2] > loc_max[2]) {

      message(
          "Inconsistent part position p->x=[%e %e %e], c->loc=[%e %e %e] "
          "c->width=[%e %e %e]",
          p->x[0], p->x[1], p->x[2], c->loc[0], c->loc[1], c->loc[2],
          c->width[0], c->width[1], c->width[2]);

      result = 0;
239
    }
240
241
242
243
244
245
246
247
248
249
250

    const float dx2 = xp->x_diff[0] * xp->x_diff[0] +
                      xp->x_diff[1] * xp->x_diff[1] +
                      xp->x_diff[2] * xp->x_diff[2];

    h_max = max(h_max, p->h);
    dx_max = max(dx_max, sqrt(dx2));
  }

  if (c->split) {
    for (int k = 0; k < 8; k++) {
251
252
253
254
      if (c->progeny[k] != NULL) {
        struct cell *cp = c->progeny[k];
        checkCellhdxmax(cp, depth);
      }
255
    }
256
257
258
259
  }

  /* Check. */
  if (c->h_max != h_max) {
260
261
    message("%d Inconsistent h_max: cell %f != parts %f", *depth, c->h_max,
            h_max);
262
    message("location: %f %f %f", c->loc[0], c->loc[1], c->loc[2]);
263
264
    result = 0;
  }
265
266
  if (c->dx_max_part != dx_max) {
    message("%d Inconsistent dx_max: %f != %f", *depth, c->dx_max_part, dx_max);
267
    message("location: %f %f %f", c->loc[0], c->loc[1], c->loc[2]);
268
269
270
271
272
273
    result = 0;
  }

  return result;
}

274
/**
275
276
 * @brief map function for dumping cells. In MPI mode locally active cells
 * only.
277
278
 */
static void dumpCells_map(struct cell *c, void *data) {
279
  size_t *ldata = (size_t *)data;
280
281
  FILE *file = (FILE *)ldata[0];
  struct engine *e = (struct engine *)ldata[1];
282
  float ntasks = c->nr_tasks;
283
284
285
  int active = (int)ldata[2];
  int mpiactive = (int)ldata[3];
  int pactive = (int)ldata[4];
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305

#if SWIFT_DEBUG_CHECKS
  /* The c->nr_tasks field does not include all the tasks. So let's check this
   * the hard way. Note pairs share the task 50/50 with the other cell. */
  ntasks = 0.0f;
  struct task *tasks = e->sched.tasks;
  int nr_tasks = e->sched.nr_tasks;
  for (int k = 0; k < nr_tasks; k++) {
    if (tasks[k].cj == NULL) {
      if (c == tasks[k].ci) {
        ntasks = ntasks + 1.0f;
      }
    } else {
      if (c == tasks[k].ci || c == tasks[k].cj) {
        ntasks = ntasks + 0.5f;
      }
    }
  }
#endif

306
  /* Only cells with particles are dumped. */
307
308
  if (c->count > 0 || c->gcount > 0 || c->scount > 0) {

309
310
/* In MPI mode we may only output cells with foreign partners.
 * These define the edges of the partitions. */
311
#if WITH_MPI
312
313
314
315
    if (mpiactive)
      mpiactive = (c->send_xv != NULL);
    else
      mpiactive = 1;
316
#else
317
    mpiactive = 1;
318
319
#endif

320
321
    /* Active cells, otherwise all. */
    if (active)
322
      active = cell_is_active_hydro(c, e);
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
    else
      active = 1;

    /* So output local super cells that are active and have MPI tasks as
     * requested. */
    if (c->nodeID == e->nodeID && (c->super == c) && active && mpiactive) {

      /* If requested we work out how many particles are active in this cell. */
      int pactcount = 0;
      if (pactive) {
        const struct part *parts = c->parts;
        for (int k = 0; k < c->count; k++)
          if (part_is_active(&parts[k], e)) pactcount++;
        struct gpart *gparts = c->gparts;
        for (int k = 0; k < c->gcount; k++)
          if (gpart_is_active(&gparts[k], e)) pactcount++;
        struct spart *sparts = c->sparts;
        for (int k = 0; k < c->scount; k++)
          if (spart_is_active(&sparts[k], e)) pactcount++;
      }

344
345
346
347
348
      fprintf(file,
              "  %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6d %6d %6d %6d %6d %6d "
              "%6.1f %20lld %6d %6d %6d %6d %6d\n",
              c->loc[0], c->loc[1], c->loc[2], c->width[0], c->width[1],
              c->width[2], e->step, c->count, c->gcount, c->scount, pactcount,
349
350
351
              c->depth, ntasks, c->ti_hydro_end_min,
              get_time_bin(c->ti_hydro_end_min), (c->super == c),
              cell_is_active_hydro(c, e), c->nodeID, c->nodeID == e->nodeID);
352
    }
353
  }
354
355
356
357
}

/**
 * @brief Dump the location, depth, task counts and timebins and active state,
358
359
 * for all cells to a simple text file. A more costly count of the active
 * particles in a cell can also be output.
360
 *
361
 * @param prefix base output filename, result is written to
362
 *               %prefix%_%rank%_%step%.dat
363
364
 * @param active just output active cells.
 * @param mpiactive just output MPI active cells, i.e. those with foreign cells.
365
 * @param pactive also output a count of active particles.
366
 * @param s the space holding the cells to dump.
367
368
 * @param rank node ID of MPI rank, or 0 if not relevant.
 * @param step the current engine step, or some unique integer.
369
 */
370
371
void dumpCells(const char *prefix, int active, int mpiactive, int pactive,
               struct space *s, int rank, int step) {
372
373
374
375
376

  FILE *file = NULL;

  /* Name of output file. */
  char fname[200];
377
  sprintf(fname, "%s_%03d_%03d.dat", prefix, rank, step);
378
379
380
  file = fopen(fname, "w");

  /* Header. */
381
  fprintf(file,
382
383
384
          "# %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s "
          "%20s %6s %6s %6s %6s %6s\n",
          "x", "y", "z", "xw", "yw", "zw", "step", "count", "gcount", "scount",
Peter W. Draper's avatar
Peter W. Draper committed
385
386
          "actcount", "depth", "tasks", "ti_end_min", "timebin", "issuper",
          "active", "rank", "local");
387

388
  size_t data[5];
389
390
  data[0] = (size_t)file;
  data[1] = (size_t)s->e;
391
392
393
  data[2] = (size_t)active;
  data[3] = (size_t)mpiactive;
  data[4] = (size_t)pactive;
394
395
396
397
  space_map_cells_pre(s, 1, dumpCells_map, &data);
  fclose(file);
}

Peter W. Draper's avatar
Peter W. Draper committed
398
399
400
#ifdef HAVE_METIS

/**
401
402
 * @brief Dump the METIS graph in standard format, simple format and weights
 * only, to a file.
Peter W. Draper's avatar
Peter W. Draper committed
403
 *
Matthieu Schaller's avatar
Matthieu Schaller committed
404
 * The standard format output can be read into the METIS
405
406
407
408
409
 * command-line tools. The simple format is just the cell connectivity (this
 * should not change between calls).  The weights format is the standard one,
 * minus the cell connectivity.
 *
 * The output filenames are generated from the prefix and the sequence number
410
411
 * of calls. So the first is called {prefix}_std_001.dat,
 *{prefix}_simple_001.dat,
Matthieu Schaller's avatar
Matthieu Schaller committed
412
 * {prefix}_weights_001.dat, etc.
413
414
415
416
417
418
419
420
421
 *
 * @param prefix base output filename
 * @param nvertices the number of vertices
 * @param nvertexweights the number vertex weights
 * @param cellconruns first part of cell connectivity info (CSR)
 * @param cellcon second part of cell connectivity info (CSR)
 * @param vertexweights weights of vertices
 * @param vertexsizes size of vertices
 * @param edgeweights weights of edges
Peter W. Draper's avatar
Peter W. Draper committed
422
 */
423
void dumpMETISGraph(const char *prefix, idx_t nvertices, idx_t nvertexweights,
424
                    idx_t *cellconruns, idx_t *cellcon, idx_t *vertexweights,
425
426
427
428
429
430
431
432
433
434
435
436
                    idx_t *vertexsizes, idx_t *edgeweights) {
  FILE *stdfile = NULL;
  FILE *simplefile = NULL;
  FILE *weightfile = NULL;
  char fname[200];
  int haveedgeweight = 0;
  int havevertexsize = 0;
  int havevertexweight = 0;
  static int nseq = 0;
  nseq++;

  if (vertexweights != NULL) {
437
    for (idx_t i = 0; i < nvertices * nvertexweights; i++) {
438
439
      if (vertexweights[i] != 1) {
        havevertexweight = 1;
Peter W. Draper's avatar
Peter W. Draper committed
440
441
442
443
        break;
      }
    }
  }
444
445

  if (vertexsizes != NULL) {
446
    for (idx_t i = 0; i < nvertices; i++) {
447
448
      if (vertexsizes[i] != 1) {
        havevertexsize = 1;
Peter W. Draper's avatar
Peter W. Draper committed
449
450
451
452
        break;
      }
    }
  }
453
454

  if (edgeweights != NULL) {
455
    for (idx_t i = 0; i < cellconruns[nvertices]; i++) {
456
457
      if (edgeweights[i] != 1) {
        haveedgeweight = 1;
Peter W. Draper's avatar
Peter W. Draper committed
458
459
460
461
462
        break;
      }
    }
  }

463
464
  /*  Open output files. */
  sprintf(fname, "%s_std_%03d.dat", prefix, nseq);
465
  stdfile = fopen(fname, "w");
466
467

  sprintf(fname, "%s_simple_%03d.dat", prefix, nseq);
468
  simplefile = fopen(fname, "w");
469
470
471

  if (havevertexweight || havevertexsize || haveedgeweight) {
    sprintf(fname, "%s_weights_%03d.dat", prefix, nseq);
472
    weightfile = fopen(fname, "w");
473
474
475
476
  }

  /*  Write the header lines. */
  fprintf(stdfile, "%" PRIDX " %" PRIDX, nvertices, cellconruns[nvertices] / 2);
477
478
  fprintf(simplefile, "%" PRIDX " %" PRIDX, nvertices,
          cellconruns[nvertices] / 2);
479
  if (havevertexweight || havevertexsize || haveedgeweight) {
480
481
    fprintf(weightfile, "%" PRIDX " %" PRIDX, nvertices,
            cellconruns[nvertices] / 2);
482

483
484
485
486
    fprintf(stdfile, " %d%d%d", havevertexsize, havevertexweight,
            haveedgeweight);
    fprintf(weightfile, " %d%d%d", havevertexsize, havevertexweight,
            haveedgeweight);
487
488
489
490

    if (havevertexweight) {
      fprintf(stdfile, " %d", (int)nvertexweights);
      fprintf(weightfile, " %d", (int)nvertexweights);
Peter W. Draper's avatar
Peter W. Draper committed
491
492
493
494
    }
  }

  /*  Write the rest of the graph. */
495
  for (idx_t i = 0; i < nvertices; i++) {
496
497
    fprintf(stdfile, "\n");
    fprintf(simplefile, "\n");
498
    if (weightfile != NULL) {
499
      fprintf(weightfile, "\n");
500
    }
501
502
503
504

    if (havevertexsize) {
      fprintf(stdfile, " %" PRIDX, vertexsizes[i]);
      fprintf(weightfile, " %" PRIDX, vertexsizes[i]);
Peter W. Draper's avatar
Peter W. Draper committed
505
506
    }

507
    if (havevertexweight) {
508
      for (idx_t j = 0; j < nvertexweights; j++) {
509
510
        fprintf(stdfile, " %" PRIDX, vertexweights[i * nvertexweights + j]);
        fprintf(weightfile, " %" PRIDX, vertexweights[i * nvertexweights + j]);
Peter W. Draper's avatar
Peter W. Draper committed
511
512
513
      }
    }

514
    for (idx_t j = cellconruns[i]; j < cellconruns[i + 1]; j++) {
515
516
517
518
519
      fprintf(stdfile, " %" PRIDX, cellcon[j] + 1);
      fprintf(simplefile, " %" PRIDX, cellcon[j] + 1);
      if (haveedgeweight) {
        fprintf(stdfile, " %" PRIDX, edgeweights[j]);
        fprintf(weightfile, " %" PRIDX, edgeweights[j]);
Peter W. Draper's avatar
Peter W. Draper committed
520
521
522
      }
    }
  }
523
524
  fprintf(stdfile, "\n");
  fprintf(simplefile, "\n");
525
  if (weightfile != NULL) {
526
    fprintf(weightfile, "\n");
527
  }
528
529
530
531
532
533

  fclose(stdfile);
  fclose(simplefile);
  if (weightfile != NULL) {
    fclose(weightfile);
  }
Peter W. Draper's avatar
Peter W. Draper committed
534
535
}

536
537
538
539
540
541
542
543
544
545
#endif /* HAVE_METIS */

#ifdef HAVE_MPI
/**
 * @brief Dump the positions and MPI ranks of the given top-level cells
 *        to a simple text file.
 *
 * Can be used to visualise the partitioning of an MPI run. Note should
 * be used immediately after repartitioning when the top-level cells
 * have been assigned their nodes. Each time this is called a new file
Matthieu Schaller's avatar
Matthieu Schaller committed
546
 * with the given prefix, a unique integer and type of .dat is created.
547
548
549
550
551
 *
 * @param prefix base output filename
 * @param cells_top the top-level cells.
 * @param nr_cells the number of cells.
 */
Matthieu Schaller's avatar
Matthieu Schaller committed
552
void dumpCellRanks(const char *prefix, struct cell *cells_top, int nr_cells) {
553
554
555
556
557
558
559
560
561
562
563
564

  FILE *file = NULL;

  /* Name of output file. */
  static int nseq = 0;
  char fname[200];
  sprintf(fname, "%s_%03d.dat", prefix, nseq);
  nseq++;

  file = fopen(fname, "w");

  /* Header. */
Matthieu Schaller's avatar
Matthieu Schaller committed
565
566
  fprintf(file, "# %6s %6s %6s %6s %6s %6s %6s\n", "x", "y", "z", "xw", "yw",
          "zw", "rank");
567
568
569
570

  /* Output */
  for (int i = 0; i < nr_cells; i++) {
    struct cell *c = &cells_top[i];
Matthieu Schaller's avatar
Matthieu Schaller committed
571
572
573
    fprintf(file, "  %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6d\n", c->loc[0],
            c->loc[1], c->loc[2], c->width[0], c->width[1], c->width[2],
            c->nodeID);
574
575
576
577
578
579
  }

  fclose(file);
}

#endif /* HAVE_MPI */
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598

/**
 * @brief parse the process /proc/self/statm file to get the process
 *        memory use (in KB). Top field in ().
 *
 * @param size     total virtual memory (VIRT)
 * @param resident resident non-swapped memory (RES)
 * @param share    shared (mmap'd) memory  (SHR)
 * @param trs      text (exe) resident set (CODE)
 * @param lrs      library resident set
 * @param drs      data+stack resident set (DATA)
 * @param dt       dirty pages (nDRT)
 */
void getProcMemUse(long *size, long *resident, long *share, long *trs,
                   long *lrs, long *drs, long *dt) {

  /* Open the file. */
  FILE *file = fopen("/proc/self/statm", "r");
  if (file != NULL) {
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
    int nscan = fscanf(file, "%ld %ld %ld %ld %ld %ld %ld", size, resident,
                       share, trs, lrs, drs, dt);

    if (nscan == 7) {
      /* Convert pages into bytes. Usually 4096, but could be 512 on some
       * systems so take care in conversion to KB. */
      long sz = sysconf(_SC_PAGESIZE);
      *size *= sz;
      *resident *= sz;
      *share *= sz;
      *trs *= sz;
      *lrs *= sz;
      *drs *= sz;
      *dt *= sz;

      *size /= 1024;
      *resident /= 1024;
      *share /= 1024;
      *trs /= 1024;
      *lrs /= 1024;
      *drs /= 1024;
      *dt /= 1024;
    } else {
      error("Failed to read sufficient fields from /proc/self/statm");
    }
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
    fclose(file);
  } else {
    error("Failed to open /proc/self/statm");
  }
}

/**
 * @brief Print the current memory use of the process. A la "top".
 */
void printProcMemUse() {
  long size;
  long resident;
  long share;
  long trs;
  long lrs;
  long drs;
  long dt;
  getProcMemUse(&size, &resident, &share, &trs, &lrs, &drs, &dt);
  printf("## VIRT = %ld , RES = %ld , SHR = %ld , CODE = %ld, DATA = %ld\n",
Matthieu Schaller's avatar
Matthieu Schaller committed
643
         size, resident, share, trs, drs);
644
645
  fflush(stdout);
}