如何使用C或C++编程获取电脑CPU使用率?如何使用C或C++获取指定进程的CPU使用率?

如何使用C或C++编程获取电脑CPU使用率?如何使用C或C++获取指定进程的CPU使用率?,第1张

得到cpu占有率的API函数:

GetSystemTimes

得到内存使用情况的API函数:

GlobalMemoryStatusEx Function

Retrieves information about the system's current usage of both physical and virtual memory.

GetPerformanceInfo Function

Retrieves the performance values contained in the PERFORMANCE_INFORMATION structure

获取特定程序的内存使用情况用:

GetProcessMemoryInfo Function

Retrieves information about the memory usage of the specified process.

#define _WIN32_WINNT   0x0501

#include <Windows.h>

#include <iostream>

using   namespace   std

__int64 CompareFileTime ( FILETIME time1, FILETIME time2 )

{

__int64 a = time1.dwHighDateTime <<32 | time1.dwLowDateTime

__int64 b = time2.dwHighDateTime <<32 | time2.dwLowDateTime

return   (b - a)

}

void main()

{

HANDLE hEvent

BOOL res

FILETIME preidleTime

FILETIME prekernelTime

FILETIME preuserTime

FILETIME idleTime

FILETIME kernelTime

FILETIME userTime

res = GetSystemTimes( &idleTime, &kernelTime, &userTime )

preidleTime = idleTime

prekernelTime = kernelTime

preuserTime = userTime

hEvent = CreateEvent (NULL,FALSE,FALSE,NULL)// 初始值扮滑为 nonsignaled ,并且每次触发后自动设置为nonsignaled

while (1){

WaitForSingleObject( hEvent,1000 )//等待500毫秒

res = GetSystemTimes( &idleTime, &kernelTime, &userTime )

int idle = CompareFileTime( preidleTime,idleTime)

int kernel = CompareFileTime( prekernelTime, kernelTime)

int user = CompareFileTime(preuserTime, userTime)

int cpu = (kernel +user - idle) *100/(kernel+user)

int cpuidle = ( idle) *100/(kernel+user)

cout <<"CPU利厅轮腊用率:" <<cpu <<"%" <<"      CPU空闲桐败率:" <<cpuidle <<"%" <<endl

preidleTime = idleTime

prekernelTime = kernelTime

preuserTime = userTime

}

}

1、Win+R打开运行对话框,输入CMD,按回车键,打开CMD命令窗口。

2、在cmd窗口中,输入命令resmon,按回车键,打开资源监视器。

3、在“资源监视器”概述弯乱中,可以清楚看到cpu使用率。同时,在CPU选项卡中可以更清楚看到cpu使用率的情况。

4、除纳蔽以上方法外,还可以埋茄档输入taskmgr 按回车键,打开“任务管理器”。

5、在“任务管理器”,“进程”项中,界面右边分别显示CPU、内存、磁盘的使用率。除此外,单击“性能”选项卡,选择CPU也可清楚看到cpu的使用率。

扩展资料:

CPU占用高原因:

原因一、硬件方面导致的CPU使用率高

其实硬件方面决定着比较大的关系,比如如果电脑还是老爷机,采用最初的单核赛扬级处理器,那么这样的电脑,在多开启几个网页的情况下就容易导致CPU使用率过高,不管怎么优化系统,这个问题始终无法很好解决,这主要是因为硬件本身过低造成的。

原因二、软件方面导致的CPU使用率高

这方面主要涉及到的是系统问题,比如系统过于臃肿,开启过多程序以及电脑中病毒木马等等都会产生CPU使用率过高,而导致电脑速度慢。解决办法主要是围绕系统优化,优化开机启动项、尽量避免开启太多程序等等。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/12332812.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-22
下一篇2023-05-22

发表评论

登录后才能评论

评论列表(0条)

    保存