1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| inline double calculate_cpu_utilization(uint64_t &last_total_time, uint64_t &last_process_time) { std::ifstream proc_stat("/proc/stat"); std::ifstream self_stat("/proc/self/stat");
if (!proc_stat.is_open() || !self_stat.is_open()) { return -1.0; }
proc_stat.seekg(0); self_stat.seekg(0);
std::string line; uint64_t user, nice, system, idle, iowait, irq, softirq, steal; uint64_t utime, stime;
if (std::getline(proc_stat, line)) { std::istringstream iss(line); iss.ignore(5, ' '); iss >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal; } else { return -1.0; }
if (std::getline(self_stat, line)) { std::istringstream iss(line); for (int i = 0; i < 13; ++i) { iss.ignore(std::numeric_limits<std::streamsize>::max(), ' '); } iss >> utime >> stime; } else { return -1.0; }
uint64_t total_time = user + nice + system + idle + iowait + irq + softirq + steal; uint64_t process_time = utime + stime;
double utilization = 0.0; if (last_total_time > 0 && last_process_time > 0) { uint64_t total_delta = total_time - last_total_time; uint64_t process_delta = process_time - last_process_time; if (total_delta > 0) { int num_cores = std::thread::hardware_concurrency(); utilization = 100.0 * process_delta / (total_delta / num_cores); } }
last_total_time = total_time; last_process_time = process_time;
return utilization; }
|