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 #include <cmath>
11 #include <fstream>
12 #include <iostream>
13 #include <cinttypes>
14 bool memoryLoad::parseMemoryFile() {
15  if(timeStamp + std::chrono::milliseconds(10) > std::chrono::steady_clock::now()) {
16  return true;
17  }
18  std::ifstream memoryFile;
19  memoryFile.open(this->memInfoFile);
20  this->timeStamp = std::chrono::steady_clock::now();
21  if (!memoryFile.is_open()) {
22  return false;
23  }
24 
25  std::string line;
26  while (std::getline(memoryFile, line)) {
27  sscanf(line.c_str(), "MemTotal: %" PRIu64, &this->totalMemoryInKB);
28  sscanf(line.c_str(), "MemAvailable: %" PRIu64, &this->currentMemoryUsageInKB);
29  }
30  memoryFile.close();
31  return true;
32 }
33 
35  this->parseMemoryFile();
36  return this->totalMemoryInKB;
37 }
38 
40  this->parseMemoryFile();
41  return this->getTotalMemoryInKB() - this->currentMemoryUsageInKB;
42 }
43 
45  this->parseMemoryFile();
46  uint64_t memavail = this->getCurrentMemUsageInKB();
47  return round((((memavail * 100.0 / this->getTotalMemoryInKB()))) * 100.0) / 100.0;
48 }
49 
51  return this->parseProcessMemoryFile(this->memInfoOfProcessFile);
52 }
53 
55  return memoryLoad::parseProcessMemoryFile("/proc/" + std::to_string(pid) + "/status");
56 }
57 
58 uint64_t memoryLoad::parseProcessMemoryFile(std::string fileToParse) {
59  uint64_t MemFree = 0;
60  std::ifstream memoryFile;
61  memoryFile.open(fileToParse);
62  std::string line;
63  while (std::getline(memoryFile, line)) {
64  sscanf(line.c_str(), "VmSize: %" PRIu64, &MemFree);
65  }
66  return MemFree;
67 }
memoryLoad::getMemoryUsageByThisProcess
uint64_t getMemoryUsageByThisProcess()
get memory usage of this process (self)
Definition: linux_memoryload.cpp:50
linux_memoryload.hpp
memoryLoad::getCurrentMemUsageInKB
uint64_t getCurrentMemUsageInKB()
get current Memory Usage of the system in KB
Definition: linux_memoryload.cpp:39
armarx::to_string
const std::string & to_string(const std::string &s)
Definition: StringHelpers.h:40
memoryLoad::getCurrentMemUsageInPercent
float getCurrentMemUsageInPercent()
get current memory usage of the system in percent 0-100%
Definition: linux_memoryload.cpp:44
memoryLoad::getTotalMemoryInKB
uint64_t getTotalMemoryInKB()
get total memory of the system in KB
Definition: linux_memoryload.cpp:34
memoryLoad::getMemoryUsedByProcess
static uint64_t getMemoryUsedByProcess(int pid)
get the current memory usage of a process
Definition: linux_memoryload.cpp:54