CMS 3D CMS Logo

memory_usage.cc
Go to the documentation of this file.
1 #include <iostream>
2 #include <dlfcn.h>
3 
4 #include "memory_usage.h"
5 
6 // see <jemalloc/jemalloc.h>
7 extern "C" {
8  typedef
9  int (*mallctl_t)(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen);
10 }
11 
12 namespace {
13  bool initialise();
14  const uint64_t * initialise_thread_allocated_p();
15  const uint64_t * initialise_thread_deallocated_p();
16 
17  const uint64_t zero = 0UL;
18  thread_local const uint64_t * thread_allocated_p = initialise_thread_allocated_p();
19  thread_local const uint64_t * thread_deallocated_p = initialise_thread_deallocated_p();
20 
21  mallctl_t mallctl = nullptr;
22  const bool have_jemalloc_and_stats = initialise();
23 
24 
25  bool initialise()
26  {
27  // check if mallctl is available, if we are using jemalloc
28  mallctl = (mallctl_t) ::dlsym(RTLD_DEFAULT, "mallctl");
29  if (mallctl == nullptr)
30  return false;
31 
32  // check if the statistics are available, if --enable-stats was specified at build time
33  bool enable_stats = false;
34  size_t bool_s = sizeof(bool);
35  mallctl("config.stats", & enable_stats, & bool_s, nullptr, 0);
36  return enable_stats;
37  }
38 
39  const uint64_t * initialise_thread_allocated_p()
40  {
41  const uint64_t * stats = & zero;
42  size_t ptr_s = sizeof(uint64_t *);
43 
44  if (have_jemalloc_and_stats)
45  // get pointers to the thread-specific allocation statistics
46  mallctl("thread.allocatedp", & stats, & ptr_s, nullptr, 0);
47 
48  return stats;
49  }
50 
51  const uint64_t * initialise_thread_deallocated_p()
52  {
53  const uint64_t * stats = & zero;
54  size_t ptr_s = sizeof(uint64_t *);
55 
56  if (have_jemalloc_and_stats)
57  // get pointers to the thread-specific allocation statistics
58  mallctl("thread.deallocatedp", & stats, & ptr_s, nullptr, 0);
59 
60  return stats;
61  }
62 
63 } // namespace
64 
66 {
67  return have_jemalloc_and_stats;
68 }
69 
71 {
72  return * thread_allocated_p;
73 }
74 
76 {
77  return * thread_deallocated_p;
78 }
79 
int(* mallctl_t)(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen)
Definition: memory_usage.cc:9
static uint64_t deallocated()
Definition: memory_usage.cc:75
static bool is_available()
Definition: memory_usage.cc:65
unsigned long long uint64_t
Definition: Time.h:15
static uint64_t allocated()
Definition: memory_usage.cc:70