NtQuerySystemInformation 在win7下无法使用,但是win10可以.

GetSystemTime在win7和win10下均可以使用.

源码来自网络.

double m_fOldCPUIdleTime;  
double m_fOldCPUKernelTime;  
double m_fOldCPUUserTime;  
typedef BOOL
(WINAPI 
 *GetSystemTimesT)(
 __out_opt LPFILETIME lpIdleTime, //空闲时间
 __out_opt LPFILETIME lpKernelTime, //内核时间
 __out_opt LPFILETIME lpUserTime //用户时间
 );

GetSystemTimesT pGetSystemTimes=(GetSystemTimesT)GetProcAddress(LoadLibrary("KERNEL32.dll"),"GetSystemTimes");
double FileTimeToDouble(FILETIME &filetime)  
{  
	return (double)(filetime.dwHighDateTime * 4.294967296E9) + (double)filetime.dwLowDateTime;  
}    
BOOL Initialize()   
{  
	FILETIME ftIdle, ftKernel, ftUser;  
	BOOL flag = FALSE;  
	if (flag = pGetSystemTimes(&ftIdle, &ftKernel, &ftUser))  
	{  
		m_fOldCPUIdleTime = FileTimeToDouble(ftIdle);  
		m_fOldCPUKernelTime = FileTimeToDouble(ftKernel);  
		m_fOldCPUUserTime = FileTimeToDouble(ftUser);  
		
	}  
	return flag;  
}
//调用Initialize后要等待1秒再调用此函数  
int GetCPUUseRate()  
{  
	int nCPUUseRate = -1;  
	FILETIME ftIdle, ftKernel, ftUser;  
	if (pGetSystemTimes(&ftIdle, &ftKernel, &ftUser))  
	{  
		double fCPUIdleTime = FileTimeToDouble(ftIdle);  
		double fCPUKernelTime = FileTimeToDouble(ftKernel);  
		double fCPUUserTime = FileTimeToDouble(ftUser);  
		nCPUUseRate= (int)(100.0 - (fCPUIdleTime - m_fOldCPUIdleTime)   
			/ (fCPUKernelTime - m_fOldCPUKernelTime + fCPUUserTime - m_fOldCPUUserTime)   
			*100.0);  
		m_fOldCPUIdleTime = fCPUIdleTime;  
		m_fOldCPUKernelTime = fCPUKernelTime;  
		m_fOldCPUUserTime = fCPUUserTime;  
	}  
	return nCPUUseRate;  
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    Initialize();
    char buf[12];
    while (true)  
    {     
	 Sleep(500);
	 wsprintf(buf, "%u", GetCPUUseRate());
	 OutputDebugString(buf);
    }  
    return 0;
}
说点什么
支持Markdown语法
在"vc6获取cpu占用率(非NtQuerySystemInformation)"已有2条评论
Loading...