Wednesday, January 16, 2013

.NET Microsoft Performance Counter does not match Task Manager

I have been struggling with this for a while now. I was asked to display the CPU usage for a list of windows servers remotely from one machine. So I wrote a piece of code that does just that using the Performance Counter. Only to find out that it returns inaccurate CPU data. I tried reading more than once, taking the normal distribution of a list of values nothing worked.

After a while it appears that you have to read .netValue once then sleep a while then read it again . Yes that is it. This fixed the problem.
Here is the code to get the real value of CPU matching the Task Manager


    Public Function getCPUPerformance(ByVal remoteHost As String) As String

        Dim userHandle As New IntPtr(0)
        LogonUser("username", "domain", "password", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, userHandle)
        Dim identity As New WindowsIdentity(userHandle)

        Dim context As WindowsImpersonationContext = identity.Impersonate()
        Dim cpuUsage As PerformanceCounter

        cpuUsage = New PerformanceCounter("Processor", "% Processor Time", "_Total", remoteHost)

        Dim val1 As Single = cpuUsage.NextValue()

        val1 = cpuUsage.NextValue()

        Thread.Sleep(50) 'You have to Sleep, otherwise you will get kinky results    
  
        val1 = cpuUsage.NextValue()


        Return val1

    End Function





3 comments:

  1. Thank you for sharing your info. I really appreciate your efforts and I am waiting for your further post thanks once again.
    Review my web site :: adobe reader Free download

    ReplyDelete
  2. Wonderful goods from you, man. I've take into account your stuff prior to and you are simply too excellent. I actually like what you have acquired right here, certainly like what you are saying and the way through which you assert it. You make it enjoyable and you continue to care for to keep it wise. I can not wait to read far more from you. That is actually a tremendous web site.
    Here is my web site :: Address signs Driveway

    ReplyDelete
  3. Thanks for ones marvelous posting! I seriously enjoyed reading
    it, you are a great author. I will be sure to bookmark your
    blog and will come back from now on. I want to encourage that
    you continue your great job, have a nice evening!
    Also see my page > http://www.pir8.net/Modules.php?name=Your_Account&op=userinfo&username=PorfirioC

    ReplyDelete

Share your thoughts

Note: Only a member of this blog may post a comment.