中易网

如何获取当前计算机CPU的占用率

答案:1  悬赏:0  
解决时间 2021-01-29 00:07
如何获取当前计算机CPU的占用率
最佳答案
内存情况比较简单 MEMORYSTATUSEX mstx; mstx.dwLength = sizeof (mstx); GlobalMemoryStatusEx( &mstx ); int iMemeryUsePercentage = mstx.dwMemoryLoad; int iTotalPhysMB = mstx.ullTotalPhys/1024/1024; int iAvailPhysMB = mstx.ullAvailPhys/1024/1024; int iTotalPageFileMB = mstx.ullTotalPageFile/1024/1024; int iAvailPageFileMB = mstx.ullAvailPageFile/1024/1024; char LogBuff[128]; memset( LogBuff , 0 , 128 ); sprintf( LogBuff , "MemAvailPct=%d%% Phys=%d/%d PageFile=%d/%d" , 100 - iMemeryUsePercentage , iAvailPhysMB , iTotalPhysMB , iAvailPageFileMB , iTotalPageFileMB ); printf("%s\n",LogBuff); 以上程序分别输出可用百分比,可以用物理内存/总物理内存,可用页面文件/总页面文件获取CPU的比较复杂,我这边只有获取单个进程CPU占用的方法,不过可以遍历所有进程分别获取再求和就是整个cpu占用率了。 #include #include typedef long long int64_t; typedef unsigned long long uint64_t; /// 时间转换 static uint64_t file_time_2_utc(const FILETIME* ftime) { LARGE_INTEGER li; li.LowPart = ftime->dwLowDateTime; li.HighPart = ftime->dwHighDateTime; return li.QuadPart; } /// 获得CPU的核数 static int get_processor_number() { SYSTEM_INFO info; GetSystemInfo(&info); return (int)info.dwNumberOfProcessors; } int get_cpu_usage(int pid) { //cpu数量 static int processor_count_ = -1; //上一次的时间 static int64_t last_time_ = 0; static int64_t last_system_time_ = 0; FILETIME now; FILETIME creation_time; FILETIME exit_time; FILETIME kernel_time; FILETIME user_time; int64_t system_time; int64_t time; int64_t system_time_delta; int64_t time_delta; int cpu = -1; if(processor_count_ == -1) { processor_count_ = get_processor_number(); } GetSystemTimeAsFileTime(&now); HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid); if (!GetProcessTimes(hProcess, &creation_time, &exit_time, &kernel_time, &user_time)) { return -1; } system_time = (file_time_2_utc(&kernel_time) + file_time_2_utc(&user_time)) / processor_count_; time = file_time_2_utc(&now); if ((last_system_time_ == 0) || (last_time_ == 0)) { last_system_time_ = system_time; last_time_ = time; return -1; } system_time_delta = system_time - last_system_time_; time_delta = time - last_time_; if (time_delta == 0) return -1; cpu = (int)((system_time_delta * 100 + time_delta / 2) / time_delta); last_system_time_ = system_time; last_time_ = time; return cpu; } int main() { while(1) { int cpu; // 参数为进程id cpu = get_cpu_usage(5160); printf("CPU使用率: %d%%\n",cpu); Sleep(1000); } return 0; }
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
富华幼儿园(天津津南)地址好找么,我有些事要
乐刷pos机两个小时以后才能刷吗
为什么猫不守家,小狗守家?
那是在铺地板前,还是把地板铺完后再清洁
株洲市分为哪四区
有人说哈尔滨铁路职业技术学院是骗人的这个事
求鲁滨逊漂流记读后感,从一个具体事例中写出
新赛季S9赛季皮肤名字叫什么
泰星push女友ann多少岁
若a>0,b>0,且ab=a+b+3,则ab的取值范围是多
lisp语言 画形状田字问题 CAD二次开发 求大神
感觉男朋友不太上进怎么办?但是他很爱我,我
下列地点中,地处热带是(  ) A.A地和B地
目前猪价正在不停下跌吗?
memopad是什么进程?
推荐资讯
急急~~~湾岸3DX+有哪些新轮胎,最好给个图,
面料中300tc
请问光纤怎么分线出去呢
1/2x+1/4÷1/10=3
Cx5买智享2驱的好呢还是四驱的好
世间多牵挂,不若乘桴浮于海 是什么意思
阿里云 云虚拟主机可以买2个吗
插上CPU供电插头后不能启动电源,不插就可以启
怎样让小人不敢惹自己
从请君试问东流水,别意与之谁短长。你能体会
上饶站有换乘通道吗?
日版的《咒怨1》好看还是《咒怨2》好看些?
手机登qq时,显示手机磁盘不足,清理后重新登
刺客的套装怎么选啊?