2)使用性能计数器计算cpu利用率
2.1)计算过程
//通过计数器获取idle空闲进程cpu占用率r1;
//通过process类的TotalProcessorTime属性获取各进程的cpu时间,求和,得各进程(除空闲进程idle,该进程无法通过process类获得cpu时间)cpu时间和t1;
//通过t1/(100-r1)得到总cpu时间t;
//对各进程,通过TotalProcessorTime获得进程cpu时间tnew,计算:
(Tnew-told)/t,即得该进程的cpu占用率,其中told是程序中记录的该进程上一次的TotalProcessorTime.
2.2)关于性能计数器
2.2)关于性能计数器
系统会为每个进程分配一个计数器,通过new PerformanceCounter("Process", "% Processor Time", "进程名称")实例化该计数器,使用计数器对象的NextValue方法可以得到进程占用cpu的百分比
(第一次调用NextValue获取的值都为0,之后就没问题了,这个要注意)。
2.3)Idle进程的含义
Idle意为懒散的、无所事事。事实上,idle不能算着一个进程,它用于表示cpu空闲资源,它所占的比率越高,表示你的机器越空闲。
2.4)多核CPU或使用超线程技术的CPU
对于多核或使用超线程技术的cpu,根据计数器求得的idle进程cpu占用比率将超过100%,此时应将idle的cpu利用率/总的cpu利用率,所得作为真正的idle的cpu利用率。
添加命名空间:
Imports System.Diagnostics
Dim mIdle As PerformanceCounter = New PerformanceCounter("Process", "% Processor Time", "Idle")
Dim mTotal As PerformanceCounter = New PerformanceCounter("Process", "% Processor Time", "_Total")
Private Sub FillNeedRefreshInfo(ParamArray ByVal pCurrentAll() As Process)
Me.mCurrentTotalCpuTime = Me.CalCurrentTotalCpuTime
Dim i As Integer = 0
Do While (i < pCurrentAll.Length)
If (pCurrentAll(i)。Id = 0) Then
Me.mDict(pCurrentAll(i)。Id)。CpuPercent = Me.mIdleCpuPercent
Else
Try Dim ms As Long = CType(pCurrentAll(i)。TotalProcessorTime.TotalMilliseconds,Long)
Dim d As Double = ((ms - Me.mDict(pCurrentAll(i)。Id)。OldCpuTime) * _
&(1 / Me.mCurrentTotalCpuTime))
Me.mDict(pCurrentAll(i)。Id)。CpuPercent = d
Me.mDict(pCurrentAll(i)。Id)。OldCpuTime = ms
Catch As System.Exception
End Try
End If
If (Not (Me.HandleProceRefresh) Is Nothing) Then
Me.HandleProceRefresh(Me.mDict(pCurrentAll(i)。Id), (100 - Me.mIdleCpuPercent))
End If
i = (i + 1)
Loop
End Sub
Private Function CalCurrentTotalCpuTime() As Double
Dim d As Double = 0
Dim idlePercent As Double = mIdle.NextValue
Dim totalPercent As Double = mTotal.NextValue
If (totalPercent = 0) Then
Me.mIdleCpuPercent = 0
Else
Me.mIdleCpuPercent = (idlePercent * (100 / totalPercent))
End If
For Each p As Process In Me.mCurrentAll
If ((p.Id = 0) _
OrElse p.HasExited) Then
'TODO: Warning!!! continue If
End If
If ((Me.mDict Is Nothing) _
OrElse Not Me.mDict.ContainsKey(p.Id)) Then
d = (d + p.TotalProcessorTime.TotalMilliseconds)
Else
d = (d _
+ (p.TotalProcessorTime.TotalMilliseconds - Me.mDict(p.Id)。OldCpuTime))
End If
Next
Return (d / (100 - mIdleCpuPercent))
End Function

