获取进程CPU占用率
获取进程CPU占用率
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | // 时间转换 static __int64 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; } // 获取进程CPU占用 int get_cpu_usage( int pid) { //cpu数量 static int processor_count_ = -1; //上一次的时间 static __int64 last_time_ = 0; static __int64 last_system_time_ = 0; FILETIME now; FILETIME creation_time; FILETIME exit_time; FILETIME kernel_time; FILETIME user_time; __int64 system_time; __int64 time ; __int64 system_time_delta; __int64 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; } |
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
原文链接:https://www.cnblogs.com/lzpong/p/3955891.html
--- auth:lzpong
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!