www.pudn.com > NetIO.rar > cpuInfo.cpp


#include "stdafx.h" 
#include "cpuInfo.h" 
 
UINT getCpuUsage() 
{ 
	PROCNTQSI NtQuerySystemInformation; 
	 
    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 -1; 
 
    // 获取cpu数量 
    status = NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL); 
    if (status != NO_ERROR) 
        return -2; 
     
	//printf("\nCPU Usage (press any key to exit):    "); 
 
	int iGet = 0; 
    while(!_kbhit() && (iGet < 2) ) 
    { 
		iGet++; 
        // 获取新的系统时间 
	    status = NtQuerySystemInformation(SystemTimeInformation,&SysTimeInfo,sizeof(SysTimeInfo),0); 
        if (status!=NO_ERROR) 
            return -3; 
 
        // 获取CPU空闲时间 
        status = NtQuerySystemInformation(SystemPerformanceInformation,&SysPerfInfo,sizeof(SysPerfInfo),NULL); 
        if (status != NO_ERROR) 
            return -4; 
 
        // 若是第一次调用,忽略 
       if (liOldIdleTime.QuadPart != 0) 
       { 
            // 差值 
            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; 
			 
            //printf("\b\b\b\b%3d%%",(UINT)dbIdleTime); 
       } 
 
        // store new CPU's idle and system time 
        liOldIdleTime = SysPerfInfo.liIdleTime; 
        liOldSystemTime = SysTimeInfo.liKeSystemTime; 
		 
        // wait one second 
        Sleep(1000); 
    } 
    return (UINT)dbIdleTime; 
}