Results 1 to 26 of 26

Thread: Cpu Utilization in vb6

Threaded View

  1. #3
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: Cpu Utilization in vb6

    Moved to the VB6 CodeBank.

    Quote Originally Posted by Bonnie West View Post
    When compared against Task Manager, the average values are oftentimes in disagreement. In fact, negative percentages are sometimes displayed. BTW, CpuTime was implicitly declared as a Variant.
    That's because the code is completely wrong. What it tries to do is to get the CPU usage information from each running process, but it updates the information inside the loop.

    Say you have 96 running processes (which is what I currently have with all services and apps that runs) then the For Each loop will loop 96 times, but it updates the textbox inside the loop and the only one you will see is the last one, where the PrevCpuTime is set to .... well, who knows? It will be something like the KernelModeTime used by the earlier process, which is not even of interest.

    To get the CPU usage you shouldn't go through the running processes, instead you should get the processor information (as opposed to process information), since modern day computers have more processor cores you have to add them up and then to get an average divide the result with the number of processors in your computer (this isn't perfect since you get an average, but it's close enough).
    Code:
    Private wmi As Object
    
    Private Sub Form_Load()
        Me.Show
        Set wmi = GetObject("winmgmts:\\.\root\CIMV2")
        Timer1.Interval = 1000
        Timer1_Timer
    End Sub
    
    
    Private Sub Timer1_Timer()
        Dim query As Object, counter As Object
        Dim percent As Double
        Set query = wmi.ExecQuery("SELECT * FROM Win32_PerfFormattedData_Counters_ProcessorInformation")
        For Each counter In query
            percent = percent + counter.PercentProcessorTime
        Next
        Text1.Text = Format(percent / query.Count, "0.00") & "%"
    End Sub
    Last edited by Joacim Andersson; Apr 18th, 2013 at 01:51 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width