请教windows高手

abraham6057 2003-12-22 05:56:03
请问在windows下如何通过c/c++调用windows api获取系统当前的cpu占用率?
(我已试过使用系统的PERF_DATA_BLOCK但查询速度太慢,同时占用的内存又太多)
急切询问
...全文
2 点赞 收藏 1
写回复
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qiaojicheng 2003-12-22
贴段代码你看看
BOOL quiet = FALSE;
UINT CpuUsage = 0;
HANDLE hThread = NULL;
DWORD thID = 0;
#define SYS_BASIC_INFO 0
#define SYS_PERFORMANCE_INFO 2
#define SYS_TIME_INFO 3

typedef struct
{
DWORD dwUnknown1;
ULONG uKeMaximumIncrement;
ULONG uPageSize;
ULONG uMmNumberOfPhysicalPages;
ULONG uMmLowestPhysicalPage;
ULONG uMmHighestPhysicalPage;
ULONG uAllocationGranularity;
PVOID pLowestUserAddress;
PVOID pMmHighestUserAddress;
ULONG uKeActiveProcessors;
BYTE bKeNumberProcessors;
BYTE bUnknown2;
WORD wUnknown3;
} SYSTEM_BASIC_INFORMATION;

typedef struct
{
LARGE_INTEGER liIdleTime;
DWORD dwSpare[76];
} SYSTEM_PERFORMANCE_INFORMATION;

typedef struct
{
LARGE_INTEGER liKeBootTime;
LARGE_INTEGER liKeSystemTime;
LARGE_INTEGER liExpTimeZoneBias;
ULONG uCurrentTimeZoneId;
DWORD dwReserved;
} SYSTEM_TIME_INFORMATION;

typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);
PROCNTQSI NtQuerySystemInformation;
#define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))

DWORD WINAPI WinNTThread( LPVOID lpParameter )
{
SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
SYSTEM_TIME_INFORMATION SysTimeInfo;
SYSTEM_BASIC_INFORMATION SysBaseInfo;
double dbIdleTime;
double dbSystemTime;
LONG status;
LARGE_INTEGER liOldIdleTime = {0,0};
LARGE_INTEGER liOldSystemTime = {0,0};

NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(
GetModuleHandle("ntdll"),
"NtQuerySystemInformation");

if (!NtQuerySystemInformation)
return 0;

// get number of processors in the system
status = NtQuerySystemInformation(SYS_BASIC_INFO, &SysBaseInfo, sizeof(SysBaseInfo), NULL);
if (status != NO_ERROR)
return 0;

while(!quiet)
{
// get new system time
status = NtQuerySystemInformation(SYS_TIME_INFO, &SysTimeInfo, sizeof(SysTimeInfo), 0);
if (status!=NO_ERROR)
return 0;

// get new CPU's idle time
status = NtQuerySystemInformation(SYS_PERFORMANCE_INFO, &SysPerfInfo, sizeof(SysPerfInfo), NULL);
if (status != NO_ERROR)
return 0;

// if it's a first call - skip it
if (liOldIdleTime.QuadPart != 0)
{
// CurrentValue = NewValue - OldValue
dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);

// CurrentCpuIdle = IdleTime / SystemTime
dbIdleTime = dbIdleTime / dbSystemTime;

// CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5;

// put cpu usage in str
CpuUsage = (UINT)dbIdleTime;
}

// store new CPU's idle and system time
liOldIdleTime = SysPerfInfo.liIdleTime;
liOldSystemTime = SysTimeInfo.liKeSystemTime;

// wait one second and start again
Sleep(1000);
}
return 0;
}
回复
发动态
发帖子
工具平台和程序库
创建于2007-09-28

2.4w+

社区成员

C/C++ 工具平台和程序库
申请成为版主
社区公告
暂无公告