File src/Memory.cpp changed (mode: 100644) (index 8d01270..6182932) |
... |
... |
void Memory::update() |
55 |
55 |
Field::setText(result.str()); |
Field::setText(result.str()); |
56 |
56 |
} |
} |
57 |
57 |
|
|
|
58 |
|
template <std::size_t N> |
|
59 |
|
bool startsWith(const std::string &str, const char (&prefix)[N]) |
|
60 |
|
{ |
|
61 |
|
return str.compare(0, N - 1, prefix) == 0; |
|
62 |
|
} |
|
63 |
|
|
|
64 |
|
template <std::size_t N> |
|
65 |
|
bool extractUint64(const std::string &str, const char (&prefix)[N], |
|
66 |
|
std::uint64_t &value) |
|
67 |
|
{ |
|
68 |
|
if (!startsWith(str, prefix)) { |
|
69 |
|
return false; |
|
70 |
|
} |
|
71 |
|
|
|
72 |
|
value = std::strtoull(str.c_str() + N, nullptr, 10); |
|
73 |
|
return true; |
|
74 |
|
} |
|
75 |
|
|
58 |
76 |
int Memory::getMemoryUsage() const |
int Memory::getMemoryUsage() const |
59 |
77 |
{ |
{ |
|
78 |
|
// Mimicking behaviour of `free` tool from `procps`, see `man free`. |
|
79 |
|
|
60 |
80 |
std::ifstream meminfo("/proc/meminfo"); |
std::ifstream meminfo("/proc/meminfo"); |
61 |
81 |
if (!meminfo.is_open()) { |
if (!meminfo.is_open()) { |
62 |
82 |
return (-1); |
return (-1); |
63 |
83 |
} |
} |
64 |
84 |
|
|
65 |
|
std::uint64_t total, free, avail, buffers, cached; |
|
66 |
|
|
|
67 |
|
meminfo.ignore(std::numeric_limits<std::streamsize>::max(), ':') >> total; |
|
68 |
|
meminfo.ignore(std::numeric_limits<std::streamsize>::max(), ':') >> free; |
|
69 |
|
meminfo.ignore(std::numeric_limits<std::streamsize>::max(), ':') >> avail; |
|
70 |
|
meminfo.ignore(std::numeric_limits<std::streamsize>::max(), ':') >> buffers; |
|
71 |
|
meminfo.ignore(std::numeric_limits<std::streamsize>::max(), ':') >> cached; |
|
72 |
|
|
|
73 |
|
meminfo.close(); |
|
|
85 |
|
std::uint64_t total = 0, free = 0, buffers = 0, cached = 0; |
|
86 |
|
for (std::string buf(64, '\0'); meminfo.getline(&buf[0], buf.size()); ) { |
|
87 |
|
std::uint64_t value; |
|
88 |
|
if (extractUint64(buf, "MemTotal:", value)) { |
|
89 |
|
total = value; |
|
90 |
|
} else if (extractUint64(buf, "MemFree:", value)) { |
|
91 |
|
free = value; |
|
92 |
|
} else if (extractUint64(buf, "Buffers:", value)) { |
|
93 |
|
buffers = value; |
|
94 |
|
} else if (extractUint64(buf, "Cached:", value)) { |
|
95 |
|
cached += value; |
|
96 |
|
} else if (extractUint64(buf, "SReclaimable:", value)) { |
|
97 |
|
cached += value; |
|
98 |
|
} |
|
99 |
|
} |
74 |
100 |
|
|
75 |
101 |
const std::uint64_t usage { |
const std::uint64_t usage { |
76 |
102 |
100 - ((free + buffers + cached)*100)/total |
100 - ((free + buffers + cached)*100)/total |