按进程ID获取进程的CPU使用率

时间:2013-02-10 21:28:43

标签: .net vb.net cpu cpu-usage pid

我有一个进程ID,我需要获得该进程的CPU使用率a.k.a %Processor Time

例如,这是一个返回AppName的CPU使用情况的简单函数:

Private Function Get_CPU_Usage(AppName as String)
   Dim AppCPU As New PerformanceCounter("Process", "% Processor Time", AppName, True)
   Return AppCPU.NextValue
End Function

这可能是错的,但这只是一个例子。

我需要做这样的事情:

Private Function Get_CPU_Usage(ProcessID as Integer)
   Dim AppCPU As New PerformanceCounter("Process", "% Processor Time", ProcessID, True)
   Return AppCPU.NextValue
End Function

注意ProcessID与AppName。我有多个以相同名称运行的进程;每个应用程序的PID都存储在我的程序中。我知道我可以迭代......

PerformanceCounter("Process", "ID Process", AppName, True)

找到流程名称,例如应用,应用#1,应用#2,但它似乎效率低下而且草率。

这里推荐的程序是什么?

1 个答案:

答案 0 :(得分:1)

感谢Hans Passant指向C#表单中的答案链接,这里是从Performance Counter by Process I instead of name转换的VB.net函数:

Public Shared Function GetProcessInstanceName(ByVal PID As Integer) As String
    Dim cat As New PerformanceCounterCategory("Process")
    Dim instances() = cat.GetInstanceNames()
    For Each instance In instances
        Using cnt As PerformanceCounter = New PerformanceCounter("Process", "ID Process", instance, True)
            Dim val As Integer = CType(cnt.RawValue, Int32)
            If val = PID Then
                Return instance
            End If
        End Using
    Next
End Function