Page 1 of 1

Detect CPU load

Posted: Tue Sep 22, 2009 12:07 pm
by Cyclops

Code: Select all

Private Declare Function GetSystemTimes Lib "kernel32.dll" (ByRef idleTime As Currency, ByRef kernelTime As Currency, ByRef userTime As Currency) As Boolean

Private Declare Sub Sleep Lib "kernel32" (ByVal millisecondsToSleep As Long)

Private Sub Command1_Click()
    
    'These are to hold the starting times values.
    Dim sIdle As Currency
    Dim sKernel As Currency
    Dim sUser As Currency
    
    
    'These variable are to hold the ending times values.
    Dim eIdle As Currency
    Dim eKernel As Currency
    Dim eUser As Currency
    
    'These will hold the values that are calculated from the ending and starting times values.
    Dim cIdle As Long
    Dim cKernel As Long
    Dim cUser As Long
    
    
    'This variable will contain the values of cKernel + cUser.
    Dim systemTime As Long
    
    'Will contain the calculated cpu usage as a percent value.
    Dim totalCpuUsage As Double
    
        
    'Retrieve the Times values before starting the delay.
    GetSystemTimes sIdle, sKernel, sUser
    sIdle = Val(sIdle)
    sKernel = Val(sKernel)
    sUser = Val(sUser)
    
    
    'The delay for how often to check and update the cpu usage values.
    'Note: You can use the sleep api if you want or the simple pause sub I added.
    Sleep (250)
    
    
    'Retrieve the Times values after the Delay.
    Call GetSystemTimes(eIdle, eKernel, eUser)
    
    
    eIdle = Val(eIdle)
    eKernel = Val(eKernel)
    eUser = Val(eUser)
    
    
    'Get the values calculated between the starting and ending Times values.
    cIdle = (eIdle - sIdle)
    cKernel = (eKernel - sKernel)
    cUser = (eUser - sUser)
    
    
    'Calculate the total system time. Which is Kernel and User time together.
    
    systemTime = (cKernel + cUser)
    DoEvents
    
    
    'Now calculate the values as a percentage based number.
    totalCpuUsage = (systemTime - cIdle) * (100) / (systemTime)
    
    'Simply display the calulated results in a label control.
    lblUsage.Caption = "Total CPU Usage: " & (totalCpuUsage) & "%"
End Sub