WinCE 下 CPU 使用率的計(jì)算方法
在函數(shù)?GetIdleTime 的用法中,MSDN 推薦的 CPU 使用率的計(jì)算方法,在部分平臺下使用時得到的使用率異常:非 0-100% 的數(shù)值。
先看看 MSDN 推薦的算法的大概實(shí)現(xiàn):
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();????//?此處為關(guān)鍵代碼?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??的計(jì)算 CPU 使用率的方法及調(diào)用示例如下:
/* //?調(diào)用示例 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); //?設(shè)置高的優(yōu)先級,保證?CPU?忙的時候也能打印?Leo hIdleThread?=?CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)IdleThread,NULL,CREATE_SUSPENDED,&dwThreadID); //?創(chuàng)建低優(yōu)先級空閑線程?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); //?計(jì)算?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); } }