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

C++ Qt开发Windows实时系统监控工具:从API采集到图表展示 系统编程是C++开发者进阶的关键方向,而理解Windows API(如GetSystemTimes、GlobalMemoryStatusEx)是掌握系统资源采集的基础。实时监控工具的核心原理是通过定时采样和增量计算,获取CPU使用率、内存占用等关键指标,并在UI层以图表形式呈现。在工程实践中,这种工具价值明显:既能锻炼多线程、界面刷新与性能优化能力,又能直接应用于日常性能诊断或进程管理。许多开发者学习Qt桌面开发时,常以图表绘制和实时刷新为切入点,但缺乏一个完整的落地场景。围绕C++与Qt构建Windows 阅读详情
AI摘要

本文介绍了一种计算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;
基于Qt与C++的跨平台系统资源监控工具开发实战 系统监控是软件开发与运维中的基础需求,它涉及对计算机核心资源(如CPU、内存、磁盘、网络)运行状态的实时感知与数据可视化。其原理通常是通过调用操作系统提供的原生API或读取系统文件(如Linux的/proc、Windows的性能计数器)来周期性采集性能数据。掌握系统监控技术对于开发高性能、高可用的软件系统具有重要价值,它能帮助开发者进行性能瓶颈分析、资源优化和故障预警。在应用场景上,从服务器运维到桌面应用开发,再到嵌入式设备管理,都离不开轻量级、定制化的监控方案。本文聚焦于使用Qt框架和C++语言,构建一个 阅读详情

相关推荐

C++ Qt QCustomPlot实时曲线绘制:从原理到高性能实现

在工业控制、数据监控和嵌入式开发中,实时数据可视化是核心需求,它涉及将动态数据流转化为直观的图形曲线。其技术原理通常基于高效的绘图库和缓冲区管理,通过优化渲染流程来保证界面的流畅性。这项技术的价值在于能够为工程师提供实时、准确的数据洞察,是构建监控系统、测试工具和数据分析平台的基础。在应用场景上,它广泛服务于传感器数据采集、网络性能监控和工业自动化等领域。本文聚焦于使用QCustomPlot这一高性能C++绘图库,深入探讨其架构原理、动态数据缓冲区设计以及性能优化技巧,特别是针对实时曲线绘制中的卡顿问题,提

weixin_34007906的博客 491

基于Qt/C++的PID实时调参可视化控件设计与实现

PID控制算法是工业自动化和嵌入式控制领域的核心,其参数整定直接影响系统响应性能。传统调参依赖反复烧录与人工观察,效率低下且难以观察到动态过程。增量式PID作为主流离散实现形式,通过输出增量避免积分饱和,结合串口通信可实现控制参数的在线调整。图形化实时曲线是观察被控对象响应的关键手段,能够直观呈现目标值、反馈值和控制量的变化。基于Qt与C++开发的上位机工具,利用QCustomPlot绘制动态波形,并将PID计算、串口协议解析与参数交互集成于一体,为电机调速、温控等场景提供了高效的工程实践方案。文章完整阐述

weixin_29192141的博客 336

基于Qt/C++的PID实时调参可视化控件实现与解析

PID控制是工业自动化与嵌入式控制中最基础也最关键的算法,其参数整定直接影响系统的稳定性和动态响应。在工程实践中,传统调参依赖修改代码、重新编译并观察串口输出的方式,流程冗长且不直观。随着上位机开发技术的普及,借助Qt框架和QCustomPlot绘图库构建实时曲线显示与参数交互界面,能够将PID调参过程转化为可视化、可在线调节的闭环操作。同时,通过串口或TCP通信将调整后的PID参数实时下发至下位机,大大缩短调试周期。该类技术尤其适用于电机调速、温度控制、机器人控制等场景,既能提升调试效率,也能为控制系统的

weixin_34082789的博客 344

Qt Creator实现CPU使用率分析

在进行应用程序开发的过程中,对CPU的使用情况进行分析可以帮助开发者优化程序性能,提高应用程序的响应速度和稳定性。本文介绍了在Qt Creator中实现CPU使用率分析的方法,主要涉及到获取CPU使用率信息、解析CPU使用率信息、显示CPU使用率信息三个部分。希望本文对大家有所帮助。其中,每个进程的CPU使用率位于第9列(%CPU),我们可以通过字符串分割的方式获取到每一行的信息,然后再提取出需要的进程ID和CPU使用率。获取到CPU使用率的信息后,需要对其进行解析,得到每个进程的CPU使用率。

m0_47037246的博客 2015

Qt实现实时显示CPU使用率(附完整源码)

Qt实现实时显示CPU使用率(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 1443

QT性能优化【CPU占用高】

如果是死循环没有msleep 一个线程大概在我电脑上占用20%start(1000);延长时间,如果ms比较小有高的占用。线程函数中使用msleep() 让出cpu避免死循环。重新这2个函数做刷新处理。

weixin_45397344的博客 477

QT/C++实时获取CPU和内存的使用率

本资源能获取电脑的CPU和内存的使用率,也能够跨平台使用包括Windows、macOS、Linux,调用方法简单,里面是一个pri文件,直接可以加在自己的工程里面,调用方法有说明

Qt实现的实时显示CPU使用率

Qt实现的实时显示CPU使用率,希望大家喜欢

计算机组成原理实验:手把手教你用模拟程序实现中断机制(附完整代码)

本文通过一个计算机组成原理模拟实验,手把手教你从零实现一个可工作的中断系统。实验详细演示了如何配置中断控制器、编写主程序与中断服务程序,并观察中断响应、现场保护和恢复的全过程,深入解析了中断原理的核心机制。

475

【NAS系统】DSM7.2部署SVN服务

早期的群晖版本可以在套件中心找到SVN Server直接安装,然后配置仓库和用户。但‌2提到DSM7.0之后套件中心没有SVN了,得用Docker。

qq_38350004的博客 4857

[数字电路]用与非门实现BCD译码器驱动数码管

Hello,大家好。这里是xdd_core,好久不见。今天来和大家聊聊大一数字电路课程的一个课设。# Key word:BCD Decoder,Proteus8.x,NAND Gate,Digital Circuit# 流程:Proteus8.x仿真电路并绘制PCB导出Gerber文件打样,最终实物验证。# 以下为我对这个课设的report(里面对整个设计做了详细介绍,并设计了完整的验证电路) 感谢观看,仅供参考,未经作者允许,禁止转载/抄袭,本文已上传至数据库,查重必挂QAQ BCD to 7-Segme

xddcore的博客 6013

ESP32 开发实战:VS Code 头文件波浪线及编译错误的终极解决方案

本文针对ESP32开发者在VS Code中常见的头文件红色波浪线和fatal error编译错误,提供了终极解决方案。通过详细讲解如何配置c_cpp_properties.json文件来修复编辑器智能提示,以及如何修改CMakeLists.txt来修正编译器路径,帮助开发者彻底解决环境配置问题,提升开发效率。

prometheus9mon的博客 295

AS7341光谱传感器实战:如何用STM32F103精准测量环境色温(附完整代码)

本文详细介绍了如何使用STM32F103驱动AS7341光谱传感器实现环境色温的精准测量。从硬件连接到驱动开发,再到色温计算算法的实现,提供了完整的代码示例和优化建议,帮助开发者在智能照明、农业监测等领域快速应用AS7341进行高精度色温检测。

weixin_30352645的博客 480

技术解析:ChangeFormer——基于Transformer的孪生网络在遥感变化检测中的创新应用

本文深入解析了ChangeFormer模型在遥感变化检测中的创新应用,该模型基于Transformer架构和孪生网络(Siamese Network),显著提升了变化检测的精度和效率。通过详细的技术实现和实战经验分享,展示了其在建筑物变化、森林监测等场景中的卓越表现,为相关领域的研究和应用提供了有力工具。

weixin_29102619的博客 499

现代密码学5.3--Hash and MAC

现代密码学5.3--Hash and MAC 博主正在学习INTRODUCTION TO MODERN CRYPTOGRAPHY (Second Edition) --Jonathan Katz, Yehuda Lindell,做一些笔记供自己回忆,如有错误请指正。整理成一个系列现代密码学,方便检索。 第二章定义了完美安全及其对应的密码方案“一次一密”, 第三章介绍了多种安全定义 3.1-3.3 计算安全,PRG和基于PRG构造的满足计算安全的密码方案; 3.4-3.5 CPA安全,PRF和基于PRF构

qq_41545715的博客 687

【推荐100个unity插件】制作美丽 Unity 景观,增强Terrain材质表现的插件——GTS

GTS地形着色器是一款专为Unity设计的强大工具,可解决地形纹理绘制和光照处理的难题。它提供一键式配置,支持实时调整地形效果,包含细节注入、高度混合、雪注入等核心功能,并兼容网格地形和低多边形模型。插件完美集成Gaia天气系统,支持HDRP细分效果。安装后通过GTS管理器创建配置文件并应用到地形,即可快速生成高质量地形渲染。其模块化设计包含全局设置、网格转换和细节调整等面板,使开发者能灵活控制地形表现,显著提升视觉效果与性能表现。

向宇的博客,专注php/web全栈 unity游戏开发,欢迎大家评论纠错 1571

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

上一篇: RabbitMQ交换机类型
下一篇: Go中变量的生命周期
云开发者联盟
博客等级 码龄5年 546粉丝 93原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值