QT/C++获取电脑CPU实时占用率

在计算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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值