在计算CPU的占用率时,我们首先了解一下CPU使用率的计算方式,无论是单个进程cpu占用率还是系统整个cpu使用率,都是一样的计算公式:
1、cpu使用率 = 运行时间 / 间隔时间
2、运行时间 = 内核时间 + 用户时间 - 空闲时间
3、间隔时间 = 内核时间 + 用户时间
因此,根据上述公式的原理,在计算CPU使用率时需要阻塞/等待线程若干时间。由于需要阻塞线程,所以计算CPU使用率的函数是绝对不能写在主线程里的,因此另开一个线程用以计算该公式。除此之外,为了方便分析,我还增加了获取磁盘占用率与内存容量的计算。代码如下:
#ifndef RESOURCE_MINITOR_H
#define RESOURCE_MINITOR_H
#include <QObject>
#include <QTimer>
#include <QProcess>
#include <QDebug>
#include <QString>
#if defined(Q_OS_LINUX)
#include "sys/statfs.h"
#else
#pragma comment(lib,"Kernel32.lib")
#pragma comment(lib,"Psapi.lib")
#include <windows.h>
#include <tlhelp32.h>
#include<direct.h>
#include<winternl.h>
#include <psapi.h>
//#include <atlconv.h>
#include <cmath>
#include <string.h>
#endif
class MySysInfo : public QObject
{
Q_OBJECT
public:
explicit MySysInfo(QObject *parent = nullptr);
private slots:
void GetResource();
public:
bool GetMemUsage(double &nMemTotal,double &nMemUsed);
bool GetNetUsage();
bool GetDiskSpeed();
bool GetCpuUsage(double &nCpuRate);
bool GetdiskSpace(unsigned long &lFreeAll,unsigned long &lTotalAll);
bool GetPathSpace(const QString & path);
private:
const int m_timer_interval__ = 1000;
QTimer monitor_timer__;
double m_send_bytes__ = 0;
double m_recv_bytes__ = 0;
double m_disk_read__ = 0;
double m_disk_write__ = 0;
double m_cpu_total__ = 0;
double m_cpu_use__ = 0;
};
#endif // RESOURCE_MINITOR_H
#include "mysysinfo.h"
MySysInfo::MySysInfo(QObject *parent) : QObject(parent)
{
connect(&monitor_timer__, &QTimer::timeout, this, &MySysInfo::GetResource);
monitor_timer__.start(m_timer_interval__);
}
void MySysInfo::GetResource()
{
double nCpuRate = 0;
GetCpuUsage(nCpuRate);
GetDiskSpeed();
double nMemTotal;
double nMem