Get CPU Usage for Process by Process ID

12,326

Thanks to Hans Passant for the link to the answer in C# form, here is the VB.net function converted from Performance Counter by Process I instead of name:

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
Share:
12,326
Brady
Author by

Brady

Updated on June 04, 2022

Comments

  • Brady
    Brady almost 2 years

    I have a process ID, and I need to get the CPU usage a.k.a % Processor Time of the process.

    For example, here is a simple function to return the CPU usage of AppName:

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

    It might be wrong but it's just an example.

    I need to do something like this:

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

    Note ProcessID vs AppName. I have multiple processes running with the same name; each application's PID is stored in my program. I know I can iterate through...

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

    to find the process name, like app, app#1, app#2, but it seems inefficient and sloppy.

    What is the recommended procedure here?