Tatooine
memory_usage.h
Go to the documentation of this file.
1#ifndef TATOOINE_MEMORY_USAGE_H
2#define TATOOINE_MEMORY_USAGE_H
3//==============================================================================
4#if defined(__unix__)
5#include <unistd.h>
6#elif defined(_WIN32) || defined(WIN32)
7#include <windows.h>
8#endif
9
10#include <fstream>
11#include <optional>
12#include <string>
13//==============================================================================
14namespace tatooine {
15//==============================================================================
17inline size_t total_memory() {
18 std::string token;
19 std::ifstream file{"/proc/meminfo"};
20 while (file >> token) {
21 if (token == "MemTotal:") {
22 unsigned long mem;
23 if (file >> mem) {
24 return mem;
25 } else {
26 throw std::runtime_error{"could not get total RAM"};
27 }
28 }
29 // ignore rest of the line
30 file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
31 }
32 throw std::runtime_error{"could not get total RAM"};
33}
34//------------------------------------------------------------------------------
37inline auto memory_usage() {
38 // 'file' stat seems to give the most reliable results
39 std::ifstream stat_stream{"/proc/self/stat", std::ios_base::in};
40
41 // dummy vars for leading entries in stat that we don't care about
42 std::string pid, comm, state, ppid, pgrp, session, tty_nr, tpgid, flags,
43 minflt, cminflt, majflt, cmajflt, utime, stime, cutime, cstime, priority,
44 nice, O, itrealvalue, starttime;
45
46 // the two fields we want
47 unsigned long vsize;
48 long rss;
49
50 stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr >>
51 tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt >> utime >>
52 stime >> cutime >> cstime >> priority >> nice >> O >> itrealvalue >>
53 starttime >> vsize >> rss;
54 // don't care about the rest
55
56 stat_stream.close();
57
58 // in case x86-64 is configured to use 2MB pages
59 auto page_size_b = sysconf(_SC_PAGE_SIZE);
60 return std::pair{vsize, rss * page_size_b};
61}
62//==============================================================================
63} // namespace tatooine
64//==============================================================================
65#endif
Definition: algorithm.h:6
size_t total_memory()
Total amount of RAM in kB.
Definition: memory_usage.h:17
auto memory_usage()
Definition: memory_usage.h:37