参考文章
https://blog.csdn.net/qq_26620783/article/details/95603453
http://blog.chinaunix.net/uid-31410005-id-5780470.html
https://blog.csdn.net/zd199218/article/details/80698192
查看cpu使用时间
cat /proc/stat | grep cpu
第一行cpu 为总的cpu运行时间 后四个为4个核各自的cpu运行时间
十个数字依次代表 user ,nice,system,idle(空闲时间),iowait,irrq,softirq,steal,guest,guest_nice
查看两次cpu的使用时间得到这段时间cpu的使用率
第一个时刻(cpu运行的总时间1)total1=十个数的总和 use1(cpu的使用的时间2)=total1-idle1
第二个时刻(cpu运行的总时间1)total2=十个数的总和 use2(cpu的使用的时间2)=total2-idle2
cpu使用率 = 该时间段cpu的使用时间/该时间段cpu运行的总时间= (use2-use1)/(total2-total1)
while(1)
{
sleep(1);
{
static uint64_t m_cpu_total[5]; //上一次的总时间 4个cpu和一个总的
static uint64_t m_cpu_use[5]; //上一次用过的时间
QString cpu_pct;
//十个数字的意义
//name user nice system idle iowait irrq softirq steal guest guest_nice
// QProcess process; QProcess 影响性能
FILE *file;
char *line;
// process.start("cat /proc/stat | grep cpu");
// process.waitForFinished();
file = popen("cat /proc/stat | grep cpu", "r");
if (NULL != file)
{
// fgets(line, 1024, file) ;
int i=0;
size_t len=0;
size_t read=0;
while ((read = getline(&line, &len, file)) != -1)
{
QString str =QLatin1String(line);
str.replace("\n","");
str.replace(QRegExp("( ){1,}")," ");
QStringList lst= str.split(" ");
if(lst.size() > 5)//防止访问越界
{
uint64_t idle = lst[4].toULong();//空闲时间
uint64_t total = 0;
uint64_t cpu_rate=0;
for(int i = 1;i < lst.size();++i)
total += lst[i].toULong();//10个时间的总和
uint64_t use=total-idle;
if(total - m_cpu_total[i] > 0)
{
// QString str1;
cpu_rate = ((use - m_cpu_use[i]) * 1000)/ (total - m_cpu_total[i]);
//str1.sprintf("1 cpu%d rate:%.2lf%%",i,cpu_rate);
if(i==0)//总的cpu使用率
{
//cpu_pct.append(QString::number(cpu_rate/10)+"."+QString::number(cpu_rate%10)+"%|") ;
}
else {//其他核cpu使用率
if(i==1)
{
cpu_pct.append(QString::number(cpu_rate/10)+"%") ;
}
else
{
cpu_pct.append(" "+QString::number(cpu_rate/10)+"%") ;
}
}
// qDebug("cpu%d rate:%ld",i,cpu_rate);
m_cpu_total[i] = total;
m_cpu_use[i] = use;
}
i++;
}
}
pclose(file);
}
qDebug()<<"cpu_pct"<<cpu_pct;
}
}
对比htop验证准确性是可用的
btw 查看cpu温度
cat /sys/class/thermal/thermal_zone0/temp