Tag Archives: processor

Calculate and Get the Computers CPUs/Processors System Usage with Visual Basic and VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 3.80 out of 5)
 

There are many reasons for wanting to get the CPU’s/Processor’s usage values. Especially for code profiling and testing. There are a couple limitations if you use this code. The GetSystemTimes() API function requires the target computer to have Windows XP with Service Pack1 and higher Operating System installed. The other is it will return the cpu usage (processor usage) based on ALL of the systems processors. Example: If the target computer has 2x CPU’s (or Cores) and one of the processors is 100% but the other cpu is 0%, then it will return 50% as the total cpu usage. Otherwise there is nothing to worry about.


Visual Basic 6.0

'

'This API Call "Requires" Windows XP with Service Pack 1 or Higher Operating System.

'More Info: http://msdn2.microsoft.com/en-us/library/ms724400.aspx

Private Declare Function GetSystemTimes Lib "kernel32.dll" (ByRef idleTime As _
    Currency, ByRef kernelTime As Currency, ByRef userTime As Currency) As Boolean
'
'Will be used to cause the applications thread to 'Sleep' or Pause/Timeout for a
'specified number of Milli-Seconds.
Private Declare Sub Sleep Lib "kernel32" (ByVal millisecondsToSleep AsLong)
'
'This variable is used to specify how often to check and display the CPU Usage value.
Dim updateSpeed As Long

 

Visual Basic.NET, Visual Basic 2008, and 2010

'

'This API Call "Requires" Windows XP with Service Pack 1 or Higher.

'More Info: http://msdn2.microsoft.com/en-us/library/ms724400.aspx

Public Declare Auto Function GetSystemTimes Lib "kernel32.dll" (ByRef idleTime As _
    Int64, ByRef kernelTime As Int64, ByRef userTime As Int64) As Boolean

'This variable is used to specify how often to check and display the CPU Usage value.

Dim updateSpeed As Integer = 250

Next we need to get the IdleTime, KernelTime, and the UserTime numbers from the GetSystemTimes() API Function. In order to get the actual cpu’s total system usage you will need to calculate the Time values from when you first got the Get System Times API and then a timeout of some sort (Its possible the longer the timeout the more accurate). After the timeout period you will want to get the values from the Get System Times() API call one more time.

Note: Since the code will take up a lot of space, I will just add the code for Visual Basic 6 for now. All you really need to do to make it work in .NET is change the variable types.

Changes to make the code below to be compatible with .NET

  • Change the Visual Basic 6.0 Long types to Integer types
  • Change the VB 6 Currency types to Long types (or Int64)
  • Change the Sleep command to the Threading.Thread.Sleep method.
  • Change Doevents() to Application.DoEvents()

Visual Basic 6.0

First you need to make 3x variables to get the first results from the GetSystemTimes api, then 3x more variables to get the GetSystemTimes values after the timeout/sleep period, and then 3x more to hold the values from subtracting the first results from the second results. (Second – First)

'
'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.
Dim cIdle As Long
Dim cKernel As Long
Dim cUser As Long

Once thats taken care I created 2x more variables for calculating purposes…

'
'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

All thats left now it to call the Get System Times API before and after the timeout, add the kernel and user results together, and finally calculate the cpu usage values and display them in a label control that I named: lblUsage.

Note: You can put the code below inside a Loop, or in a Timer control.


'
'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(updateSpeed)
'
'Retrieve the Times values after the Delay.
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) & "%"

CPU Usage Example using GetSystemTimes()


That’s all there is to it!  Have fun!

Jason

Use the Registry to get CPU/Processor Hardware information using VB.NET and Higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

This is a simple article/tip of using the Windows System Registry to access the ‘CentralProcessor’ sub-key and extract information about the computers processor. You can get the cpu’s clockspeed, namestring, model, stepping, etc. Shows two ways to access the registry.

Example use is below.


Visual Basic.NET, Visual Basic 2008, and VB 2010

        'The registry path to get the info we are wanting.
        Dim str As String = "HARDWARE\DESCRIPTION\System\CentralProcessor"

        'Returns how many SubKeys are under “CentralProcessor”.
        'The subKey count under this key =’s the‘total cpu’s your system has installed.
        'My system happens to return 2x subkeys since I have a Dual Core system.
        Dim cpuCount As Integer = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(str, False).SubKeyCount
        '
        'Get and add the values for the first cpu.
        '
        Dim cpuMhz As String = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( _
            "HARDWARE\DESCRIPTION\System\CentralProcessor\0").GetValue("~mhz")

        Dim cpuName As String = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( _
            "HARDWARE\DESCRIPTION\System\CentralProcessor\0").GetValue("ProcessorNameString")

        Dim cpuVendorID As String = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( _
            "HARDWARE\DESCRIPTION\System\CentralProcessor\0").GetValue("VendorIdentifier")

        Dim cpuIdentifier As String = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( _
            "HARDWARE\DESCRIPTION\System\CentralProcessor\0").GetValue("Identifier")

Thats all there is to it. You just need to handle the variables that will contain the cpu data extracted. Below is similar example code for VB 05, and higher only since it uses the MY interface to access the registry…


Visual Basic 2005/2008 and VB 2010 Only…

        'The registry path to get the info we are wanting.
        Dim str As String = "HARDWARE\DESCRIPTION\System\CentralProcessor"

        'Returns how many SubKeys are under “CentralProcessor”.
        'The subKey count under this key =’s the‘total cpu’s your system has installed.
        'Of course, 90% or so will only have 1x subkey denoting a‘single cpu system.
        'My system happens to return 2x subkeys since I have a Dual Core system.
        Dim cpuCount As Integer = My.Computer.Registry.LocalMachine.OpenSubKey(str, False).SubKeyCount

        'Get and add the values for the first cpu.

        Dim cpuMhz As String = My.Computer.Registry.LocalMachine.OpenSubKey( _
            "HARDWARE\DESCRIPTION\System\CentralProcessor\0").GetValue("~mhz")

        Dim cpuName As String = My.Computer.Registry.LocalMachine.OpenSubKey( _
            "HARDWARE\DESCRIPTION\System\CentralProcessor\0").GetValue("ProcessorNameString")

        Dim cpuVendorID As String = My.Computer.Registry.LocalMachine.OpenSubKey( _
            "HARDWARE\DESCRIPTION\System\CentralProcessor\0").GetValue("VendorIdentifier")

        Dim cpuIdentifier As String = My.Computer.Registry.LocalMachine.OpenSubKey( _
            "HARDWARE\DESCRIPTION\System\CentralProcessor\0").GetValue("Identifier")

For VB 6.0 it’s not quite this simple to access the registry. Win32 API calls are required to do so. There are examples around the net that shows how to use the Win32 Registry code in VB 6.0. Have fun!

Jason

Find out how many CPU’s/Processors/Cores the computer has installed using VB.NET and Higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

Its actually very easy with Visual Basic.NET VB 2008, VB.NET 2010, 2013, and Higher to detect the cpu or core count for the computer. Below is the very simple way to do it which will return the total number of logical processors installed in the computer…

        '
        'This works for Visual Basic 2005 and Higher.
        '
        'The code we want is under the System.Environment Namespace and is the ProcessorCount
        'property.
        MsgBox(System.Environment.ProcessorCount.ToString)

What if you want to get the CPU/Processor/Core count with Visual Basic.NET 2002 or 2003?

Well, .NET version 1.1 and older does not have the ProcessorCount property like version 2.0 of the .NET Framework. But that doesn’t mean it can’t be done. Its actually not to awfully hard to do. Below is a way to do it using the Windows system Registry…

        '
        'The registry path to get the info we are wanting.
        Dim str As String = "HARDWARE\DESCRIPTION\System\CentralProcessor"
        '
        'Returns how many SubKeys are under “CentralProcessor”. The subKey count under this key
        '=’s the‘total cpu’s your system has installed. Of course, 90% or so will only have 1x
        'subkey denoting a ‘single cpu system. My system happens to return 2x subkeys since I
        'have a Dual Core system.
        Dim cpuCount As Integer = My.Computer.Registry.LocalMachine.OpenSubKey(str, False).SubKeyCount

        MsgBox(cpuCount.ToString)

The Messagebox will then throw a Dialog with the total number of cpu’s/core’s on the current computer. I do not know though if this works on all Windows operating systems.

You can also use the Windows Management Instrumentation (WMI) and get the total instances of the class.

Below is a simple way to use WMI to return the computers CPU/Core Count…

       '
        'Create a Instrument Class and Object.
        Dim wmiClass As New System.Management.ManagementClass
        Dim wmiObject As New System.Management.ManagementObject
        '
        'Set the PAth to “Win32_Processor” which is where we want to get info.
        wmiClass.Path.RelativePath = "Win32_Processor"
        '
        'Last of all, just check how many instances is available and that will be your cpu/core count.
        MsgBox(wmiClass.GetInstances.Count)

Executing the code above will tell you how many cpus are on the computer since there is a class instance for each CPU/processor/core on the current computer.

Take care 🙂

                       Jason

Revised: 2015