Qt 获取系统内存使用率,CPU使用率,硬盘容量(windows、linux都可用)
作者:互联网
我写了个获取系统资源的类,通过宏定义的方式区分了linux下和windows下各运行不同的代码。
头文件:
1 #ifndef RESOURCE_MINITOR_H 2 #define RESOURCE_MINITOR_H 3 #include <QObject> 4 #include <QTimer> 5 #include <QProcess> 6 #include <QDebug> 7 #include <QString> 8 #if defined(Q_OS_LINUX) 9 #include "sys/statfs.h" 10 #else 11 #pragma comment(lib,"Kernel32.lib") 12 #pragma comment(lib,"Psapi.lib") 13 #include <windows.h> 14 #include <tlhelp32.h> 15 #include<direct.h> 16 #include<winternl.h> 17 #include <psapi.h> 18 //#include <atlconv.h> 19 #include <cmath> 20 #include <string.h> 21 #endif 22 23 class MySysInfo : public QObject 24 { 25 Q_OBJECT 26 public: 27 explicit MySysInfo(QObject *parent = nullptr); 28 private slots: 29 void GetResource(); 30 public: 31 bool GetMemUsage(double &nMemTotal,double &nMemUsed); 32 bool GetNetUsage(); 33 bool GetDiskSpeed(); 34 bool GetCpuUsage(double &nCpuRate); 35 bool GetdiskSpace(unsigned long &lFreeAll,unsigned long &lTotalAll); 36 bool GetPathSpace(const QString & path); 37 private: 38 const int m_timer_interval__ = 1000; 39 QTimer monitor_timer__; 40 double m_send_bytes__ = 0; 41 double m_recv_bytes__ = 0; 42 double m_disk_read__ = 0; 43 double m_disk_write__ = 0; 44 double m_cpu_total__ = 0; 45 double m_cpu_use__ = 0; 46 }; 47 #endif // RESOURCE_MINITOR_H
源文件:
1 #include "mysysinfo.h" 2 MySysInfo::MySysInfo(QObject *parent) : QObject(parent) 3 { 4 connect(&monitor_timer__, &QTimer::timeout, this, &MySysInfo::GetResource); 5 monitor_timer__.start(m_timer_interval__); 6 } 7 void MySysInfo::GetResource() 8 { 9 double nCpuRate = 0; 10 GetCpuUsage(nCpuRate); 11 GetDiskSpeed(); 12 double nMemTotal; 13 double nMemUsed; 14 GetMemUsage(nMemTotal,nMemUsed); 15 GetNetUsage(); 16 unsigned long lFreeAll; 17 unsigned long lTotalAll; 18 GetdiskSpace(lFreeAll,lTotalAll); 19 GetPathSpace("/"); 20 qDebug()<<"\n"; 21 } 22 bool MySysInfo::GetMemUsage(double &nMemTotal,double &nMemUsed) 23 { 24 #if defined(Q_OS_LINUX) 25 QProcess process; 26 process.start("free -m"); //使用free完成获取 27 process.waitForFinished(); 28 process.readLine(); 29 QString str = process.readLine(); 30 str.replace("\n",""); 31 str.replace(QRegExp("( ){1,}")," ");//将连续空格替换为单个空格 用于分割 32 auto lst = str.split(" "); 33 if(lst.size() > 6) 34 { 35 qDebug("mem total:%.0lfMB free:%.0lfMB",lst[1].toDouble(),lst[6].toDouble()); 36 nMemTotal = lst[1].toDouble(); 37 nMemUsed = nMemTotal-lst[6].toDouble(); 38 return true; 39 } 40 else 41 { 42 return false; 43 } 44 #else 45 MEMORYSTATUSEX memsStat; 46 memsStat.dwLength = sizeof(memsStat); 47 if(!GlobalMemoryStatusEx(&memsStat))//如果获取系统内存信息不成功,就直接返回 48 { 49 return false; 50 } 51 double nMemFree = memsStat.ullAvailPhys/( 1024.0*1024.0 ); 52 nMemTotal = memsStat.ullTotalPhys/( 1024.0*1024.0 ); 53 nMemUsed= nMemTotal- nMemFree; 54 qDebug("windows:mem total:%.0lfMB,use:%.0lfMB",nMemTotal,nMemUsed); 55 return true; 56 #endif 57 } 58 bool MySysInfo::GetNetUsage() 59 { 60 #if defined(Q_OS_LINUX) 61 QProcess process; 62 process.start("cat /proc/net/dev"); //读取文件/proc/net/dev获取网络收发包数量,再除取样时间得到网络速度 63 process.waitForFinished(); 64 process.readLine(); 65 process.readLine(); 66 while(!process.atEnd()) 67 { 68 QString str = process.readLine(); 69 str.replace("\n",""); 70 str.replace(QRegExp("( ){1,}")," "); 71 auto lst = str.split(" "); 72 if(lst.size() > 9 && lst[0] == "enp2s0:") 73 { 74 double recv = 0; 75 double send = 0; 76 if(lst.size() > 1) 77 recv = lst[1].toDouble(); 78 if(lst.size() > 9) 79 send = lst[9].toDouble(); 80 qDebug("%s 接收速度:%.0lfbyte/s 发送速度:%.0lfbyte/s",lst[0].toStdString().c_str(),(recv - m_recv_bytes__) / (m_timer_interval__ / 1000.0),(send - m_send_bytes__) / (m_timer_interval__ / 1000.0)); 81 m_recv_bytes__ = recv; 82 m_send_bytes__ = send; 83 } 84 } 85 #endif 86 return true; 87 } 88 #if defined(Q_OS_WIN32) 89 __int64 Filetime2Int64(const FILETIME* ftime) 90 { 91 LARGE_INTEGER li; 92 li.LowPart = ftime->dwLowDateTime; 93 li.HighPart = ftime->dwHighDateTime; 94 return li.QuadPart; 95 } 96 97 __int64 CompareFileTime(FILETIME preTime,FILETIME nowTime) 98 { 99 return Filetime2Int64(&nowTime) - Filetime2Int64(&preTime); 100 } 101 #endif 102 bool MySysInfo::GetCpuUsage(double &nCpuRate) 103 { 104 nCpuRate = -1; 105 #if defined(Q_OS_LINUX) 106 QProcess process; 107 process.start("cat /proc/stat"); 108 process.waitForFinished(); 109 QString str = process.readLine(); 110 str.replace("\n",""); 111 str.replace(QRegExp("( ){1,}")," "); 112 auto lst = str.split(" "); 113 if(lst.size() > 3) 114 { 115 double use = lst[1].toDouble() + lst[2].toDouble() + lst[3].toDouble(); 116 double total = 0; 117 for(int i = 1;i < lst.size();++i) 118 total += lst[i].toDouble(); 119 if(total - m_cpu_total__ > 0) 120 { 121 qDebug("cpu rate:%.2lf%%",(use - m_cpu_use__) / (total - m_cpu_total__) * 100.0); 122 m_cpu_total__ = total; 123 m_cpu_use__ = use; 124 nCpuRate = (use - m_cpu_use__) / (total - m_cpu_total__) * 100.0; 125 return true; 126 } 127 } 128 #else 129 HANDLE hEvent; 130 bool res; 131 static FILETIME preIdleTime; 132 static FILETIME preKernelTime; 133 static FILETIME preUserTime; 134 FILETIME idleTime; 135 FILETIME kernelTime; 136 FILETIME userTime; 137 res = GetSystemTimes(&idleTime,&kernelTime,&userTime); 138 preIdleTime = idleTime; 139 preKernelTime = kernelTime; 140 preUserTime = userTime; 141 hEvent = CreateEvent(nullptr,FALSE,FALSE,nullptr);//初始值为nonsignaled 142 WaitForSingleObject(hEvent,500);//等待500毫秒 143 res = GetSystemTimes(&idleTime,&kernelTime,&userTime); 144 long long idle = CompareFileTime(preIdleTime,idleTime); 145 long long kernel = CompareFileTime(preKernelTime,kernelTime); 146 long long user = CompareFileTime(preUserTime,userTime); 147 nCpuRate =ceil( 100.0*( kernel + user - idle ) / ( kernel + user ) ); 148 qDebug()<<"windows:CPU use rate:"<<nCpuRate<<"%"; 149 #endif 150 return true; 151 } 152 bool MySysInfo::GetDiskSpeed() 153 { 154 #if defined(Q_OS_LINUX) 155 QProcess process; 156 process.start("iostat -k -d"); 157 process.waitForFinished(); 158 process.readLine(); 159 process.readLine(); 160 process.readLine(); 161 QString str = process.readLine(); 162 str.replace("\n",""); 163 str.replace(QRegExp("( ){1,}")," "); 164 auto lst = str.split(" "); 165 if(lst.size() > 5) 166 { 167 qDebug("disk read:%.0lfkb/s disk write:%.0lfkb/s",(lst[4].toDouble() - m_disk_read__ ) / (m_timer_interval__ / 1000.0),(lst[5].toDouble() - m_disk_write__) / (m_timer_interval__ / 1000.0)); 168 m_disk_read__ = lst[4].toDouble(); 169 m_disk_write__ = lst[5].toDouble(); 170 return true; 171 } 172 #endif 173 return false; 174 } 175 bool MySysInfo::GetdiskSpace(unsigned long &lFreeAll,unsigned long &lTotalAll) 176 { 177 #if defined(Q_OS_LINUX) 178 QProcess process; 179 process.start("df -k"); 180 process.waitForFinished(); 181 process.readLine(); 182 while(!process.atEnd()) 183 { 184 QString str = process.readLine(); 185 if(str.startsWith("/dev/sda")) 186 { 187 str.replace("\n",""); 188 str.replace(QRegExp("( ){1,}")," "); 189 auto lst = str.split(" "); 190 if(lst.size() > 5) 191 qDebug("挂载点:%s 已用:%.0lfMB 可用:%.0lfMB",lst[5].toStdString().c_str(),lst[2].toDouble()/1024.0,lst[3].toDouble()/1024.0); 192 lFreeAll += lst[2].toDouble()/1024.0; 193 lTotalAll += lst[3].toDouble()/1024.0+lFreeAll; 194 } 195 } 196 #else 197 198 static char path[_MAX_PATH];//存储当前系统存在的盘符 199 int curdrive = _getdrive(); 200 lFreeAll = 0UL; 201 lTotalAll = 0UL; 202 for(int drive = 1; drive <= curdrive; drive++ )//遍历所有盘符 203 { 204 if( !_chdrive( drive ) ) 205 { 206 sprintf(path, "%c:\\", drive + 'A' - 1 ); 207 ULARGE_INTEGER caller, total, free; 208 WCHAR wszClassName[_MAX_PATH]; 209 memset(wszClassName,0,sizeof(wszClassName)); 210 MultiByteToWideChar(CP_ACP,0,path,strlen(path)+1,wszClassName, 211 sizeof(wszClassName)/sizeof(wszClassName[0])); 212 if (GetDiskFreeSpaceEx(wszClassName, &caller, &total, &free) == 0) 213 { 214 qDebug()<<"GetDiskFreeSpaceEx Filed!"; 215 return false; 216 } 217 218 double dTepFree = free.QuadPart/( 1024.0*1024.0 ); 219 double dTepTotal = total.QuadPart/( 1024.0*1024.0 ); 220 qDebug()<<"Get Windows Disk Information:"<<path<<"--free:"<<dTepFree<<"MB,--total:"<<dTepTotal<<"MB"; 221 lFreeAll += ceil(dTepFree); 222 lTotalAll += ceil(dTepTotal); 223 } 224 } 225 qDebug("Total disk capacity:%lu MB,Free disk capacity:%lu MB",lTotalAll,lFreeAll); 226 #endif 227 return true; 228 } 229 bool MySysInfo::GetPathSpace(const QString & path) 230 { 231 #if defined(Q_OS_LINUX) 232 struct statfs diskInfo;//需要#include "sys/statfs.h" 233 statfs(path.toUtf8().data(), &diskInfo); 234 qDebug("%s 总大小:%.0lfMB 可用大小:%.0lfMB",path.toStdString().c_str(),(diskInfo.f_blocks * diskInfo.f_bsize)/1024.0/1024.0,(diskInfo.f_bavail * diskInfo.f_bsize)/1024.0/1024.0); 235 #endif 236 return true; 237 }
标签:__,include,Qt,process,double,硬盘容量,lst,toDouble,使用率 来源: https://www.cnblogs.com/ybqjymy/p/13862489.html