Click here to Skip to main content
15,906,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to get the CPU time like in the task manager but the values and processes i am getting are not matching what is displayed in the task manager.

This is the code i am using,

VB
Public Shared Function getAllProcesses() As List(Of ServProcess)
    Dim procLST As New List(Of ServProcess)
    Dim ProcID As Integer
    Dim ret As New ServProcess
    Try
        Dim MyobjectQuery As New System.Management.ObjectQuery("select * from Win32_Process")

        Dim MySearcher As New System.Management.ManagementObjectSearcher(MyobjectQuery)
        For Each Mgmt As System.Management.ManagementObject In MySearcher.Get()

            Dim m_Process As New ServProcess

            m_Process.Name = Mgmt("Name")

            ProcID = Mgmt("ProcessID")

            If ProcID <> 0 Then

                ret = GetUssage(ProcID)

                m_Process.ProcessTime = ret.ProcessTime
                m_Process.CpuVal = ret.CpuVal

                If m_Process.ProcessTime IsNot Nothing And m_Process.Name IsNot Nothing And m_Process.CpuVal IsNot Nothing Then
                    If m_Process.ProcessTime <> "" Then
                        procLST.Add(m_Process)
                    End If
                End If

            End If

        Next
    Catch ex As Exception

    End Try

    Return procLST
End Function

Public Shared Function GetUssage(ByVal pid As String) As ServProcess
    'get the process
    Dim MyobjectQuery As New System.Management.ObjectQuery("select * from Win32_Process WHERE ProcessID = " + pid)
    Dim MySearcher As New System.Management.ManagementObjectSearcher(MyobjectQuery)

    Dim ProcessorUsage As Decimal
    Dim msPassed As Decimal


    Dim ret As New ServProcess

    For Each Mgmt As System.Management.ManagementObject In MySearcher.Get()

        Dim currentTime As DateTime = DateTime.Now

        Try
            Dim firstSample, secondSample As DateTime
            Dim ProcessorTime As String

            firstSample = DateTime.Now
            Mgmt.Get()

            Dim u_OldCPU As Long = CType(Mgmt.Properties("UserModeTime").Value, ULong) + CType(Mgmt.Properties("KernelModeTime").Value, ULong)

            secondSample = DateTime.Now
            Mgmt.Get()

            Dim u_newCPU As ULong = CType(Mgmt.Properties("UserModeTime").Value, ULong) + CType(Mgmt.Properties("KernelModeTime").Value, ULong)

            msPassed = CType((secondSample - firstSample).TotalMilliseconds, Decimal)

            ProcessorUsage = CType(u_newCPU - u_OldCPU, Decimal) / (msPassed * 100 * Environment.ProcessorCount)

            Dim mDate As DateTime = CDate(Mid(Mgmt("CreationDate"), 5, 2) & "/" & Mid(Mgmt("CreationDate"), 7, 2) & "/" & Left(Mgmt("CreationDate"), 4) & " " & Mid(Mgmt("CreationDate"), 9, 2) & ":" & Mid(Mgmt("CreationDate"), 11, 2) & ":" & Mid(Mgmt("CreationDate"), 13, 2))

            Dim ProcessorSpan As TimeSpan = currentTime.Subtract(mDate)

            ProcessorTime = ProcessorSpan.Days.ToString("000") & ":" & ProcessorSpan.Hours.ToString("00") & ":" & ProcessorSpan.Minutes.ToString("00")

            ret.Name = ""
            ret.CpuVal = ProcessorUsage.ToString("0.00")
            ret.ProcessTime = ProcessorTime

        Catch ex As Exception

        End Try
    Next

    Return ret

End Function


I am not sure if i am going about this the wrong way or if there is a better more efficient way to do this.

So I guess my question is what is the best way to get these values to display them in a datagrid view in a windows form.

thanks
Posted

This is what you will need to query CPU usage:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa394277%28v=vs.85%29.aspx[^].

There is a number of code samples with some cookbook recipes for WMI query which you can easily find if you Google; for example:
http://bit.ly/QMh4rI[^].

Just one relevant code sample:
http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/469ec6b7-4727-4773-9dc7-6e3de40e87b8/[^].

And this is the CodeProject article on the topic:
http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/469ec6b7-4727-4773-9dc7-6e3de40e87b8/[^].

Nice and short introductory article:
http://www.csharphelp.com/2006/10/wmi-made-easy-for-c/[^].

Good luck,
—SA
 
Share this answer
 
Comments
DinoRondelly 23-Nov-12 16:42pm    
Thank you for the reply
Sergey Alexandrovich Kryukov 23-Nov-12 17:43pm    
You are welcome.
--SA
This is what i ended up doing

VB
Public Shared Function getAllProcesses() As List(Of ServProcess)
    Dim procLST As New List(Of ServProcess)

    Dim mprocess As Array

    mprocess = Process.GetProcesses()
    Try
        For Each p As Process In mprocess
            Dim mProc As New ServProcess

            Dim processorTimeCounter As PerformanceCounter = New PerformanceCounter("Process", "% Processor Time", p.ProcessName)

            Try

                processorTimeCounter.NextValue()

                Threading.Thread.Sleep(500)

                Dim ts As TimeSpan = p.TotalProcessorTime
                Dim dt As DateTime = DateTime.MinValue.Add(ts)
                Dim s As String
                s = dt.ToString("HH:mm:ss") ' custom DateTime formatting

                mProc.Name = p.ProcessName
                mProc.CpuVal = processorTimeCounter.NextValue.ToString("0:00") + "%"
                mProc.ProcessTime = s

                If mProc.ProcessTime = "00:00:00" Then
                Else
                    procLST.Add(mProc)
                End If

            Catch ex As Exception

            End Try

        Next

        procLST.Sort(Function(x, y) y.ProcessTime.CompareTo(x.ProcessTime))
        Return procLST
    Catch ex As Exception

    End Try

    Return procLST

End Function
 
Share this answer
 
Comments
patrickjadams1002 28-Jul-15 13:46pm    
what class is "ServProcess" part of?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900