博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
windows 下检测进程cpu使用率
阅读量:4165 次
发布时间:2019-05-26

本文共 2268 字,大约阅读时间需要 7 分钟。

以下内容主要来自 ,对其中的一些细节进行了调整。

最近在项目中需要监测某个进程的CPU使用率,原本以为是一个很简单的需求,想用Windows上的性能计数器来进行计算的,但是经过尝试之后,发现Windows性能计数器算出来的值根本不正确,不耐经过互联网的搜索,终于发现了以下计算方法,总的测试,发现结果还是比较精准的。

其实Windows的进程使用率计算出来的在一段很短的时间内,计算某进程使用CPU的时间,除以所有进程使用CPU的时间,即为该进程的CPU使用率。具体代码如下:

#include <stdafx.h>

#include 
#include
#include
using namespace std;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 get_cpu_usage(pid); } system_time_delta = system_time - last_system_time_; time_delta = time - last_time_; if (time_delta == 0) return get_cpu_usage(pid); cpu = (int)((system_time_delta * 100 + time_delta / 2) / time_delta); last_system_time_ = system_time; last_time_ = time; return cpu;}int main() { int cpu; int process_id; // 参数为进程id cin>>process_id; while(1) { cpu = get_cpu_usage(process_id); printf("CPU使用率: %d%%\n",cpu); Sleep(1000); } return 0;}

转载:

你可能感兴趣的文章
MongoDB配置--docker进阶
查看>>
0-1背包问题--动态规划C#Demo解析
查看>>
背包问题--贪心算法C#Demo解析
查看>>
EA逆向工程--逆向生成实体属性图
查看>>
J2EE规范-入门学习
查看>>
9月英语月刊--thinking
查看>>
0-1背包问题-回溯&贪心算法-C#Demo
查看>>
c++函数学习
查看>>
17年10月自考--一直在路上~
查看>>
docker部署swagger
查看>>
excel导入导出--Java
查看>>
创建一个项目--[Angular入门]
查看>>
aspx,ascx和ashx使用小结
查看>>
$再学习--JS进阶(一)
查看>>
Linux部署jboss引发的思考
查看>>
jdbc.properties数据库连接配置
查看>>
AJAX之XMLHttpRequest--验证(一)
查看>>
Hibernate之初见(一)
查看>>
Hibernate之初见(二)
查看>>
说说Action和Jsp页面交互的那些事
查看>>