linux下获取cpu个数之C++实现

  1. 新建一个cpu_num.cpp文件
    touch cpu_num.cpp
  2. 写入如下代码
   #include<iostream>
   	#include<unistd.h>
   	using namespace std;

   	int main()
   	{
   		 int cpu_num;
       		cpu_num = sysconf(_SC_NPROCESSORS_CONF);
       		cout<<"cpu_num="<<cpu_num<<endl;
       		return 0;
}
  1. 编译成可执行程序
    g++ -o cpu_num cpu_num.cpp
  2. 执行程序,得到结果
    ./cpu_num
    在这里插入图片描述
你可以使用Linux下的/proc文件系统来获取CPU总使用率。其中,/proc/stat文件提供了当前系统的CPU使用情况,包括总CPU时间、空闲CPU时间、用户CPU时间、系统CPU时间等。你可以通过读取/proc/stat文件并解析其中的数据,计算出CPU的总使用率。 以下是获取CPU总使用率的C++代码示例: ``` #include <iostream> #include <fstream> #include <sstream> #include <thread> #include <chrono> using namespace std; double GetCPULoad() { ifstream proc_stat("/proc/stat"); string line; getline(proc_stat, line); istringstream iss(line); string cpu; long long user, nice, sys, idle, iowait, irq, softirq, steal, guest, guest_nice; iss >> cpu >> user >> nice >> sys >> idle >> iowait >> irq >> softirq >> steal >> guest >> guest_nice; long long PrevIdle = idle + iowait; long long PrevNonIdle = user + nice + sys + irq + softirq + steal; long long PrevTotal = PrevIdle + PrevNonIdle; this_thread::sleep_for(chrono::milliseconds(100)); // sleep for a short time to get the current CPU usage proc_stat.seekg(0); getline(proc_stat, line); istringstream iss2(line); iss2 >> cpu >> user >> nice >> sys >> idle >> iowait >> irq >> softirq >> steal >> guest >> guest_nice; long long Idle = idle + iowait; long long NonIdle = user + nice + sys + irq + softirq + steal; long long Total = Idle + NonIdle; // calculate CPU usage percentage double CPU_Percentage = (double)(Total - PrevTotal) / (double)(Total - PrevTotal + PrevIdle - Idle); return CPU_Percentage; } int main() { // print CPU usage percentage every second while (true) { cout << "CPU usage: " << GetCPULoad() * 100 << "%" << endl; this_thread::sleep_for(chrono::seconds(1)); } return 0; } ``` 该代码会每秒钟输出一次CPU使用率。你可以根据需要修改输出内容和时间间隔。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值