33 this->cpuLoadMap = this->parseStatFile(this->procFile);
34 this->currentTime = std::chrono::system_clock::now();
35 std::this_thread::sleep_for(std::chrono::milliseconds(100));
37 this->upDateCPUUsage();
41 cpuLoad::upDateCPUUsage()
43 if (!((this->currentTime + std::chrono::milliseconds(10)) > std::chrono::system_clock::now()))
45 this->oldCpuLoadMap = this->cpuLoadMap;
46 this->currentTime = std::chrono::system_clock::now();
47 this->cpuLoadMap = this->parseStatFile(this->procFile);
48 this->calculateCpuUsage();
56 this->upDateCPUUsage();
57 return this->cpuUsage.at(
"cpu");
63 this->upDateCPUUsage();
64 std::vector<double> percents;
65 for (
const auto& elem : this->cpuUsage)
67 if (elem.first ==
"cpu")
71 percents.push_back(elem.second);
77 cpuLoad::calculateCpuUsage()
79 for (
const auto& elem : this->cpuLoadMap)
81 if (this->cpuLoadMap.at(elem.first).at(
"user") <
82 this->oldCpuLoadMap.at(elem.first).at(
"user") ||
83 this->cpuLoadMap.at(elem.first).at(
"nice") <
84 this->oldCpuLoadMap.at(elem.first).at(
"nice") ||
85 this->cpuLoadMap.at(elem.first).at(
"system") <
86 this->oldCpuLoadMap.at(elem.first).at(
"system") ||
87 this->cpuLoadMap.at(elem.first).at(
"idle") <
88 this->oldCpuLoadMap.at(elem.first).at(
"idle"))
93 auto total = (this->cpuLoadMap.at(elem.first).at(
"user") -
94 this->oldCpuLoadMap.at(elem.first).at(
"user")) +
95 (this->cpuLoadMap.at(elem.first).at(
"nice") -
96 this->oldCpuLoadMap.at(elem.first).at(
"nice")) +
97 (this->cpuLoadMap.at(elem.first).at(
"system") -
98 this->oldCpuLoadMap.at(elem.first).at(
"system"));
100 double percent = total;
101 total += (this->cpuLoadMap.at(elem.first).at(
"idle") -
102 this->oldCpuLoadMap.at(elem.first).at(
"idle"));
105 this->cpuUsage[elem.first] = percent;
110 std::map<std::string, std::unordered_map<std::string, uint64_t>>
111 cpuLoad::parseStatFile(
const std::string& fileName)
114 std::map<std::string, std::unordered_map<std::string, uint64_t>> cpuLoad_;
118 std::ifstream cpuFile(fileName);
120 uint32_t lineCnt = 0;
121 bool infoValid =
true;
122 for (std::string line; std::getline(cpuFile, line) && infoValid; lineCnt++)
125 std::stringstream strStream(line);
129 std::unordered_map<std::string, uint64_t> cpuValues;
130 while (strStream >> strPart)
134 if (strPart.find(
"cpu") != std::string::npos)
147 cpuValues[it->data()] = std::stoull(strPart);
157 cpuLoad_[cpuNum] = cpuValues;
161 catch (std::ifstream::failure& e)
163 throw std::runtime_error(
"Exception: " + fileName + std::string(e.what()));
172 if (!this->cpuName.empty())
174 return this->cpuName;
178 file.open(cpuNameFile);
182 throw std::runtime_error(
"unable to open " + cpuNameFile);
185 while (std::getline(file, line))
187 if (line.find(
"model name") != std::string::npos)
189 size_t pos = line.find(
':');
190 if (pos != std::string::npos)
192 this->cpuName = line.substr(pos, line.size());
193 return this->cpuName;
197 return std::string();