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  */
9 #include "linux_memoryload.hpp"
10 
11 #include <cinttypes>
12 #include <cmath>
13 #include <fstream>
14 #include <iostream>
15 
16 bool
17 memoryLoad::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 
41 uint64_t
43 {
44  this->parseMemoryFile();
45  return this->totalMemoryInKB;
46 }
47 
48 uint64_t
50 {
51  this->parseMemoryFile();
52  return this->getTotalMemoryInKB() - this->currentMemoryUsageInKB;
53 }
54 
55 float
57 {
58  this->parseMemoryFile();
59  uint64_t memavail = this->getCurrentMemUsageInKB();
60  return round((((memavail * 100.0 / this->getTotalMemoryInKB()))) * 100.0) / 100.0;
61 }
62 
63 uint64_t
65 {
66  return this->parseProcessMemoryFile(this->memInfoOfProcessFile);
67 }
68 
69 uint64_t
71 {
72  return memoryLoad::parseProcessMemoryFile("/proc/" + std::to_string(pid) + "/status");
73 }
74 
75 uint64_t
76 memoryLoad::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 }
memoryLoad::getMemoryUsageByThisProcess
uint64_t getMemoryUsageByThisProcess()
get memory usage of this process (self)
Definition: linux_memoryload.cpp:64
linux_memoryload.hpp
memoryLoad::getCurrentMemUsageInKB
uint64_t getCurrentMemUsageInKB()
get current Memory Usage of the system in KB
Definition: linux_memoryload.cpp:49
armarx::to_string
const std::string & to_string(const std::string &s)
Definition: StringHelpers.h:41
memoryLoad::getCurrentMemUsageInPercent
float getCurrentMemUsageInPercent()
get current memory usage of the system in percent 0-100%
Definition: linux_memoryload.cpp:56
memoryLoad::getTotalMemoryInKB
uint64_t getTotalMemoryInKB()
get total memory of the system in KB
Definition: linux_memoryload.cpp:42
memoryLoad::getMemoryUsedByProcess
static uint64_t getMemoryUsedByProcess(int pid)
get the current memory usage of a process
Definition: linux_memoryload.cpp:70