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(); }
分类:
B.1.1-C/C++ 基础
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?