30 this->cpuLoadMap = this->parseStatFile(this->procFile);
31 this->currentTime = std::chrono::system_clock::now();
32 std::this_thread::sleep_for(std::chrono::milliseconds(100));
34 this->upDateCPUUsage();
37 void cpuLoad::upDateCPUUsage() {
38 if (!((this->currentTime + std::chrono::milliseconds(10)) > std::chrono::system_clock::now())) {
39 this->oldCpuLoadMap = this->cpuLoadMap;
40 this->currentTime = std::chrono::system_clock::now();
41 this->cpuLoadMap = this->parseStatFile(this->procFile);
42 this->calculateCpuUsage();
49 this->upDateCPUUsage();
50 return this->cpuUsage.at(
"cpu");
54 this->upDateCPUUsage();
55 std::vector<double> percents;
56 for (
const auto &elem: this->cpuUsage) {
57 if (elem.first ==
"cpu") {
60 percents.push_back(elem.second);
65 void cpuLoad::calculateCpuUsage() {
66 for (
const auto &elem: this->cpuLoadMap) {
67 if (this->cpuLoadMap.at(elem.first).at(
"user") < this->oldCpuLoadMap.at(elem.first).at(
"user") ||
68 this->cpuLoadMap.at(elem.first).at(
"nice") < this->oldCpuLoadMap.at(elem.first).at(
"nice") ||
69 this->cpuLoadMap.at(elem.first).at(
"system") < this->oldCpuLoadMap.at(elem.first).at(
"system") ||
70 this->cpuLoadMap.at(elem.first).at(
"idle") < this->oldCpuLoadMap.at(elem.first).at(
"idle")) {
72 auto total = (this->cpuLoadMap.at(elem.first).at(
"user") - this->oldCpuLoadMap.at(elem.first).at(
"user")) +
73 (this->cpuLoadMap.at(elem.first).at(
"nice") - this->oldCpuLoadMap.at(elem.first).at(
"nice")) +
74 (this->cpuLoadMap.at(elem.first).at(
"system") - this->oldCpuLoadMap.at(elem.first).at(
"system"));
76 double percent = total;
77 total += (this->cpuLoadMap.at(elem.first).at(
"idle") - this->oldCpuLoadMap.at(elem.first).at(
"idle"));
80 this->cpuUsage[elem.first] = percent;
87 std::map<std::string, std::unordered_map<std::string, uint64_t>> cpuLoad::parseStatFile(
const std::string &fileName) {
89 std::map<std::string, std::unordered_map<std::string, uint64_t>> cpuLoad_;
92 std::ifstream cpuFile(fileName);
95 bool infoValid =
true;
96 for (std::string line; std::getline(cpuFile, line) && infoValid; lineCnt++) {
98 std::stringstream strStream(line);
102 std::unordered_map<std::string, uint64_t> cpuValues;
103 while (strStream >> strPart) {
104 if (cpuNum.empty()) {
105 if (strPart.find(
"cpu") != std::string::npos) {
114 cpuValues[it->data()] = std::stoull(strPart);
121 if (!cpuNum.empty()) {
122 cpuLoad_[cpuNum] = cpuValues;
125 }
catch (std::ifstream::failure &e) {
126 throw std::runtime_error(
"Exception: " + fileName + std::string(e.what()));
133 if (!this->cpuName.empty()) {
134 return this->cpuName;
138 file.open(cpuNameFile);
140 if (!file.is_open()) {
141 throw std::runtime_error(
"unable to open " + cpuNameFile);
144 while (std::getline(file, line)) {
145 if (line.find(
"model name") != std::string::npos) {
146 size_t pos = line.find(
':');
147 if (pos != std::string::npos) {
148 this->cpuName = line.substr(pos, line.size());
149 return this->cpuName;
153 return std::string();