C++获取cpu核数,使用效率

获取cpu核数,使用率

#include <sys/sysinfo.h>
#include <sys/statvfs.h>
#include <fstream>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include <sstream>
struct CpuInfo {
    std::string user;
    long long nice;
    long long system;
    long long idle;
    long long iowait;
    long long irq;
    long long softirq;
    long long steal;
    long long guest;
    long long guest_nice;
    long long total;
};

CpuInfo read_cpu_info(std::istream& file) {
    CpuInfo info;
    file >> info.user >> info.nice >> info.system >> info.idle >> info.iowait >> info.irq >> info.softirq >> info.steal >> info.guest >> info.guest_nice >> info.total;
    return info;
}

double calculate_cpu_usage(const CpuInfo& prev, const CpuInfo& curr) {
    long long prev_total = prev.nice + prev.system + prev.idle + prev.iowait + prev.irq + prev.softirq + prev.steal;
    long long curr_total = curr.nice + curr.system + curr.idle + curr.iowait + curr.irq + curr.softirq + curr.steal;
    long long total_diff = curr_total - prev_total;
    long long idle_diff = curr.idle - prev.idle;
    return static_cast<double>(total_diff - idle_diff) / total_diff;
}

void checkCpu(){
    // 获取 CPU 信息
    std::ifstream cpuinfo("/proc/cpuinfo");
    std::string line;
    while(getline(cpuinfo, line)) {
        if(line.substr(0, 10) == "model name") {
            std::cout << "CPU: " << line << std::endl;
        }
    }

    
    std::ifstream file("/proc/stat");
     line = "";
    std::getline(file, line);  // 跳过第一行

    std::vector<CpuInfo> prev_info;
    while (std::getline(file, line)) {
        if (line.substr(0, 3) == "cpu") {
            std::stringstream ss(line);
            prev_info.push_back(read_cpu_info(ss));
        } else {
            break;
        }
    }
    std::this_thread::sleep_for(std::chrono::seconds(1));
    file.seekg(0);
    std::getline(file, line);  // 跳过第一行
    std::vector<CpuInfo> curr_info;
    while (std::getline(file, line)) {
        if (line.substr(0, 3) == "cpu") {
            std::stringstream ss(line);
            curr_info.push_back(read_cpu_info(ss));
        } else {
            break;
        }
    }

    for (size_t i = 0; i < prev_info.size(); ++i) {
        std::cout << "CPU:" << i << " ,Usage: " << calculate_cpu_usage(prev_info[i], curr_info[i]) << std::endl;
    }
}


int main(){
    checkCpu();
}

 

posted @ 2024-03-27 06:20  He_LiangLiang  阅读(29)  评论(0编辑  收藏  举报