WinCE 下 CPU 使用率的计算方法
扫描二维码
随时随地手机看文章
在函数 GetIdleTime 的用法中,MSDN 推荐的 CPU 使用率的计算方法,在部分平台下使用时得到的使用率异常:非 0-100% 的数值。
先看看 MSDN 推荐的算法的大概实现:
static void CallCountCpuIdleThread(CCountCpuDlg *pCCountCpuDlg) { DWORD dwStartTick; DWORD dwIdleStart; DWORD dwStopTick; DWORD dwIdleEnd; int nPresentIdle; int nCpuUage[10]={0}; int nCount=0; int ave=0; DWORD sum=0; int i; while(1) { dwStartTick=GetTickCount(); // 此处为关键代码 Leo.Zheng dwIdleStart=GetIdleTime(); Sleep(100); dwStopTick=GetTickCount(); dwIdleEnd=GetIdleTime(); nPresentIdle=(100*(dwIdleEnd-dwIdleStart))/((dwStopTick-dwStartTick)); // 算法多次的一个平均值 Leo.Zheng if(nCount<10) { nCpuUage[nCount]=nPresentIdle; nCount++; if(nCount==10) { for(i=0;i<10;i++) sum+=nCpuUage[i]; ave=sum/10; // g_nCpuIdle only read in the main thread g_nCpuIdle=ave; nCount=0; sum=0; //RETAILMSG(1,(TEXT("CPU laoding is %d /r/n"),ave)); } } } }
不使用 GetIdleTime 的计算 CPU 使用率的方法及调用示例如下:
/* // 调用示例 DWORD dwThreadID = 0; HANDLE hThread = NULL; hThread = CreateThread(NULL,0,ThreadPrintCpuLoad,this,0,&dwThreadID); if(NULL != hThread) { CloseHandle(hThread); } */ static DWORD GetThreadTick(FILETIME *pFtKernel, FILETIME *pFtUser) { __int64 iKernel64 = 0; __int64 iUser64 = 0; iKernel64 = pFtKernel->dwHighDateTime; iKernel64 <dwLowDateTime; iUser64 = pFtUser->dwHighDateTime; iUser64 <dwLowDateTime; iKernel64 += iUser64; // nano sec to milli sec iKernel64 /= 10000; return (DWORD)iKernel64; } static void IdleThread(LPVOID pvParams) { while(1) { } } static DWORD ThreadPrintCpuLoad(LPVOID lpParameter) { DWORD dwThreadID = 0; HANDLE hIdleThread = NULL; SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_HIGHEST); // 设置高的优先级,保证 CPU 忙的时候也能打印 Leo hIdleThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)IdleThread,NULL,CREATE_SUSPENDED,&dwThreadID); // 创建低优先级空闲线程 Leo.Zheng SetThreadPriority(hIdleThread,THREAD_PRIORITY_IDLE); ResumeThread(hIdleThread); while(1) { Sleep(1000); // 1S打印一次 Leo.Zheng static DWORD dwLastThreadTime = 0; static DWORD dwLastTickTime = 0; DWORD dwCurrentThreadTime = 0; DWORD dwCurrentTickTime = 0; DWORD dwCpuPower = 0; FILETIME ftCreationTime; FILETIME ftExitTime; FILETIME ftKernelTime; FILETIME ftUserTime; SuspendThread(hIdleThread); dwCurrentTickTime = GetTickCount(); GetThreadTimes(hIdleThread,&ftCreationTime,&ftExitTime,&ftKernelTime,&ftUserTime); dwCurrentThreadTime = GetThreadTick(&ftKernelTime,&ftUserTime); // 计算 CPU 占用率 if(dwCurrentTickTime != dwLastTickTime || 0 != dwLastThreadTime || 0 != dwLastTickTime) { dwCpuPower = 100 - (((dwCurrentThreadTime - dwLastThreadTime) * 100) / (dwCurrentTickTime - dwLastTickTime)); } else { dwCpuPower = 0; } // save status dwLastTickTime = GetTickCount(); dwLastThreadTime = dwCurrentThreadTime; printf("CPU loaded: %d%%rn",dwCpuPower); ResumeThread(hIdleThread); } }