Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to get CPU usage?

Status
Not open for further replies.

pho01

Programmer
Mar 17, 2003
218
US
PercentProcessorTime of WMI object can get a CPU usage of a process, however, I need to get the CPU usage of a machine (all processes), how do I alternate the codes below to perform just that?

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
set PerfProcess = objWMIService.Get(_
"Win32_PerfFormattedData_PerfProc_Process.Name='Idle'")

While (True)
PerfProcess.Refresh_
Wscript.Echo PerfProcess.PercentProcessorTime
Wscript.Sleep 1000
Wend

Thanks!
 
I think there is an API for that
Some time ago I used the Public Declare Sub GlobalMemoryStatus Lib "kernel32" (lpmstMemStat As MemoryStatus) to get available memory and there is a similar one for CPU
 
Win32_PerfFormattedData_PerfOS_Processor.Name='_Total' may offer something along the lines you are interested in investigating. Note that it is only available in XP onwards (so XP, 2003, Vista)
 
You can also use the GetSystemTimes API function. This function is also only available in Win XP, 2003 and Vista.

Start a new VB project, place a timer control on your form and set its Interval to 1000.

Try running the following code.
___
[tt]
Option Explicit
Private Declare Function GetSystemTimes Lib "kernel32" (lpIdleTime As Any, lpKernelTime As Any, lpUserTime As Any) As Long
Private Sub Timer1_Timer()
Dim it As Currency, kt As Currency, ut As Currency
Static it1 As Currency, kt1 As Currency, ut1 As Currency
GetSystemTimes it, kt, ut
it1 = it - it1
kt1 = kt - kt1
ut1 = ut - ut1
Caption = FormatPercent((kt1 + ut1 - it1) / (kt1 + ut1), 0)
it1 = it
kt1 = kt
ut1 = ut
End Sub[/tt]
___

Note that the times returned by GetSystemTimes function are in cumulative / totalized form.
The expression it1 = it - it1 computes the idle time between the current and the last sample; and so on.

Due to this the very first CPU usage calculated will not be correct because the last time values (it1, kt1 and ut1) will not be initialized.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top