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 int (*mallctl_t)(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen);
9 }
10 
11 namespace {
12  bool initialise();
13  const uint64_t *initialise_thread_allocated_p();
14  const uint64_t *initialise_thread_deallocated_p();
15 
16  const uint64_t zero = 0UL;
17  thread_local const uint64_t *thread_allocated_p = initialise_thread_allocated_p();
18  thread_local const uint64_t *thread_deallocated_p = initialise_thread_deallocated_p();
19 
20  mallctl_t mallctl = nullptr;
21  const bool have_jemalloc_and_stats = initialise();
22 
23  bool initialise() {
24  // check if mallctl is available, if we are using jemalloc
25  mallctl = (mallctl_t)::dlsym(RTLD_DEFAULT, "mallctl");
26  if (mallctl == nullptr)
27  return false;
28 
29  // check if the statistics are available, if --enable-stats was specified at build time
30  bool enable_stats = false;
31  size_t bool_s = sizeof(bool);
32  mallctl("config.stats", &enable_stats, &bool_s, nullptr, 0);
33  return enable_stats;
34  }
35 
36  const uint64_t *initialise_thread_allocated_p() {
37  const uint64_t *stats = &zero;
38  size_t ptr_s = sizeof(uint64_t *);
39 
40  if (have_jemalloc_and_stats)
41  // get pointers to the thread-specific allocation statistics
42  mallctl("thread.allocatedp", &stats, &ptr_s, nullptr, 0);
43 
44  return stats;
45  }
46 
47  const uint64_t *initialise_thread_deallocated_p() {
48  const uint64_t *stats = &zero;
49  size_t ptr_s = sizeof(uint64_t *);
50 
51  if (have_jemalloc_and_stats)
52  // get pointers to the thread-specific allocation statistics
53  mallctl("thread.deallocatedp", &stats, &ptr_s, nullptr, 0);
54 
55  return stats;
56  }
57 
58 } // namespace
59 
60 bool memory_usage::is_available() { return have_jemalloc_and_stats; }
61 
62 uint64_t memory_usage::allocated() { return *thread_allocated_p; }
63 
64 uint64_t memory_usage::deallocated() { return *thread_deallocated_p; }
int(* mallctl_t)(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen)
Definition: memory_usage.cc:8
static uint64_t deallocated()
Definition: memory_usage.cc:64
static bool is_available()
Definition: memory_usage.cc:60
unsigned long long uint64_t
Definition: Time.h:13
static uint64_t allocated()
Definition: memory_usage.cc:62