linux_memoryload.cpp
Go to the documentation of this file.
1/**
2 * @author: Daniel Fuchs
3 * @contact: fuxeysolutions@gmail.com
4 *
5 * distributed under the MIT License (MIT).
6 * Copyright (c) Daniel Fuchs
7 *
8 */
10
11#include <cinttypes>
12#include <cmath>
13#include <fstream>
14#include <iostream>
15
16bool
17memoryLoad::parseMemoryFile()
18{
19 if (timeStamp + std::chrono::milliseconds(10) > std::chrono::steady_clock::now())
20 {
21 return true;
22 }
23 std::ifstream memoryFile;
24 memoryFile.open(this->memInfoFile);
25 this->timeStamp = std::chrono::steady_clock::now();
26 if (!memoryFile.is_open())
27 {
28 return false;
29 }
30
31 std::string line;
32 while (std::getline(memoryFile, line))
33 {
34 sscanf(line.c_str(), "MemTotal: %" PRIu64, &this->totalMemoryInKB);
35 sscanf(line.c_str(), "MemAvailable: %" PRIu64, &this->currentMemoryUsageInKB);
36 }
37 memoryFile.close();
38 return true;
39}
40
41uint64_t
43{
44 this->parseMemoryFile();
45 return this->totalMemoryInKB;
46}
47
48uint64_t
50{
51 this->parseMemoryFile();
52 return this->getTotalMemoryInKB() - this->currentMemoryUsageInKB;
53}
54
55float
57{
58 this->parseMemoryFile();
59 uint64_t memavail = this->getCurrentMemUsageInKB();
60 return round((((memavail * 100.0 / this->getTotalMemoryInKB()))) * 100.0) / 100.0;
61}
62
63uint64_t
65{
66 return this->parseProcessMemoryFile(this->memInfoOfProcessFile);
67}
68
69uint64_t
71{
72 return memoryLoad::parseProcessMemoryFile("/proc/" + std::to_string(pid) + "/status");
73}
74
75uint64_t
76memoryLoad::parseProcessMemoryFile(std::string fileToParse)
77{
78 uint64_t MemFree = 0;
79 std::ifstream memoryFile;
80 memoryFile.open(fileToParse);
81 std::string line;
82 while (std::getline(memoryFile, line))
83 {
84 sscanf(line.c_str(), "VmSize: %" PRIu64, &MemFree);
85 }
86 return MemFree;
87}
uint64_t getTotalMemoryInKB()
get total memory of the system in KB
uint64_t getMemoryUsageByThisProcess()
get memory usage of this process (self)
float getCurrentMemUsageInPercent()
get current memory usage of the system in percent 0-100%
uint64_t getCurrentMemUsageInKB()
get current Memory Usage of the system in KB
static uint64_t getMemoryUsedByProcess(int pid)
get the current memory usage of a process