A temporary task was received yesterday, and it was time to postpone the actual work of a worker thread until the CPU was idle. At that time, the first feeling is that the thread priority is set to the idle level, that only the CPU is idle to run the thread, in fact, it should not, after all, the instant is idle level also need to queue, but the priority is low. Of course, can not say that the CPU is idle to execute, it should be said that the utilization rate is relatively low time to perform more appropriate.
Reference blog: http://www.cnblogs.com/TenosDoIt/p/3242910.html, describes a number of ways to describe how to calculate CPU usage.
I tried two ways, using the PDH of VS to calculate the seemingly not-so-accurate, but using getsystemtimers to calculate the basic and the Task Manager display is very close, this code is followed:
//CpuRate.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<Windows.h>#include<cstdio>#include<conio.h>classccpuuserate{ Public: BOOL Initialize () {FILETIME ftidle, Ftkernel, Ftuser; BOOL Flag=FALSE; if(flag = Getsystemtimes (&ftidle, &ftkernel, &Ftuser)) {M_foldcpuidletime=filetimetodouble (Ftidle); M_foldcpukerneltime=filetimetodouble (Ftkernel); M_foldcpuusertime=filetimetodouble (Ftuser); } returnFlag; } //wait 1 or so seconds after calling initialize to call this function intgetcpuuserate () {intNcpuuserate =-1; FILETIME Ftidle, Ftkernel, Ftuser; if(Getsystemtimes (&ftidle, &ftkernel, &Ftuser)) { DoubleFcpuidletime =filetimetodouble (Ftidle); DoubleFcpukerneltime =filetimetodouble (Ftkernel); DoubleFcpuusertime =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; } returnncpuuserate; }Private: DoubleFiletimetodouble (FILETIME &filetime) { return(Double) (Filetime.dwhighdatetime *4.294967296E9) + (Double) Filetime.dwlowdatetime; }Private: DoubleM_foldcpuidletime; DoubleM_foldcpukerneltime; Doublem_foldcpuusertime;};intMain () { Do{ccpuuserate cpuuserate; if(!cpuuserate.initialize ()) {printf ("Workthread: Initialization of system usage time failed with error code%d", GetLastError ()); Break; } while(true) {Sleep ( +); intLicpuuserrate =cpuuserate.getcpuuserate (); printf ("\ r The current CPU utilization is:%4d%%", licpuuserrate); } } while(false); return 0;}
CPU Usage Calculation