20 static const std::list<std::string> stats {
"pid",
61 "delaycct_blkio_ticks",
74 this->findProcesses();
75 return this->procCPUUsage;
79 void linuxProcessLoad::calculateProcessLoad() {
80 auto [ cpuTotalUserTime, cpuTotalUserLowTime, cpuTotalSysTime, cpuTotalIdleTime] = CpuTimes;
82 auto [ oldCpuTotalUserTime, oldCpuTotalUserLowTime, oldCpuTotalSysTime, oldCpuTotalIdleTime] = oldCpuTimes;
83 auto TotalUserTime = cpuTotalUserTime - oldCpuTotalUserTime;
84 auto TotalSysTime = cpuTotalSysTime - oldCpuTotalSysTime;
86 this->procCPUUsage.clear();
87 for(
const auto& elem: processStat) {
88 auto pid = elem.first;
90 auto oldProc = oldProcessStat.at(pid);
91 auto proc = elem.second;
92 auto procName = proc.at(
"comm");
94 cpuTime += (std::stoull(proc.at(
"utime")) - std::stoull(oldProc.at(
"utime")));
95 cpuTime += (std::stoull(proc.at(
"stime")) - std::stoull(oldProc.at(
"stime")));
98 double percentage = ((
static_cast<double>(cpuTime) *100.0) /
static_cast<double>((TotalUserTime + TotalSysTime)) );
100 if(percentage > 0.1) {
101 this->procCPUUsage[procName] = percentage;
105 std::cerr <<
"process: " << pid <<
" disappeared in meantime" << std::endl;
111 void linuxProcessLoad::findProcesses() {
113 auto cpuMonitoring = std::make_unique<cpuLoad>(
"/proc/stat");
115 this->CpuTimes = cpuMonitoring->getCpuTimes();
118 std::string path{
"/proc/"};
119 std::vector<std::string> processes;
120 for(
auto& elem: std::filesystem::directory_iterator(path)) {
121 auto procPath = elem.path().string();
123 procPath.erase(procPath.begin(), procPath.begin() +
static_cast<int32_t
>(path.size()));
124 if (std::isdigit(procPath.at(0))) {
125 if (!std::count_if(procPath.begin(), procPath.end(), [](
auto c) {
126 return std::isalpha(c);
128 parseProcess(procPath);
133 this->calculateProcessLoad();
135 this->oldProcessStat = this->processStat;
136 this->oldCpuTimes = this->CpuTimes;
139 void linuxProcessLoad::parseProcess(
const std::string& pid) {
140 std::string path {
"/proc/" + pid +
"/stat"};
141 std::ifstream ethFile(path);
144 std::unordered_map<std::string, std::string> procStat;
145 auto identifierStart = stats.begin();
150 bool isProcessFound =
false;
151 while (ethFile >> strPart) {
153 if(identifierStart != stats.end()) {
155 procStat[identifierStart->data()] +=
" " + strPart;
157 if(std::count_if(strPart.begin(),strPart.end(),[](
auto c) { return c ==
'('; })) {
158 isProcessFound =
true;
159 procStat[identifierStart->data()] = strPart;
161 if(!isProcessFound) {
162 procStat[identifierStart->data()] = strPart;
166 if(std::count_if(strPart.begin(), strPart.end(), [] (
auto c) { return c ==
')';})) {
167 isProcessFound =
false;
171 if(!isProcessFound) {
178 procStat[
"comm"].erase(std::remove_if(procStat[
"comm"].begin(),procStat[
"comm"].end(), [](
auto c) {
179 return c ==
'(' ||
c ==
')';
180 }), procStat[
"comm"].end());
181 processStat[pid] = procStat;