linux获取cpu使用率(sy%+us%)
float getCpuUsage()
{
// C++11兼容的元组解包
typedef std::tuple<unsigned long long, unsigned long long, unsigned long long> CpuTuple;
auto parseCpuLine = [](const std::string& line) -> CpuTuple {
std::istringstream iss(line);
iss.ignore(3, ' '); // 跳过 "cpu"
while (iss.peek() == ' ' || iss.peek() == '\t') iss.ignore();
// 解析所有字段(含 steal、guest、guest_nice)
unsigned long long user = 0, nice = 0, system = 0, idle = 0,
iowait = 0, irq = 0, softirq = 0, steal = 0,
guest = 0, guest_nice = 0;
iss >> user >> nice >> system >> idle >> iowait >> irq >> softirq
>> steal >> guest >> guest_nice;
// 计算用户态和系统态时间(us% = user + nice, sy% = system + irq + softirq)
unsigned long long us_time = user + nice;
unsigned long long sy_time = system + irq + softirq;
// 总时间包含所有字段 [11](@ref)
unsigned long long total = user + nice + system + idle + iowait +
irq + softirq + steal + guest + guest_nice;
return std::make_tuple(us_time, sy_time, total);
};
// 第一次采样
std::ifstream file1("/proc/stat");
std::string line1;
std::getline(file1, line1);
unsigned long long us1, sy1, total1;
std::tie(us1, sy1, total1) = parseCpuLine(line1);
sleep(1);
// 第二次采样
std::ifstream file2("/proc/stat");
std::string line2;
std::getline(file2, line2);
unsigned long long us2, sy2, total2;
std::tie(us2, sy2, total2) = parseCpuLine(line2);
// 计算差值
const unsigned long long total_diff = total2 - total1;
if (total_diff == 0) return 0.0f;
const unsigned long long us_diff = us2 - us1;
const unsigned long long sy_diff = sy2 - sy1;
return static_cast<float>(us_diff + sy_diff) * 100.0f / total_diff;
}