Jump to content
Sign in to follow this  
Ascend4nt

Process CPU Usage Trackers

Recommended Posts

Ascend4nt

Process CPU Usage Trackers


As yet another alternative to the Performance Counters UDF, I've created this UDF to allow easy tracking of one or more processes's CPU usage.  While this has obviously been done before, I haven't seen it done the way I've created it.

Basically, just as the Performance Counters had Process Counter objects, so this too has Process Usage trackers.  They are relatively simple to use, and require very little interaction other than invoking the functions.

To create a new tracker object, call one of these:

_ProcessUsageTracker_Create()   ; Single process tracker
_ProcessesUsageTracker_Create() ; Multiple processes tracker

The multiple-process tracker requires addition of processes, which can be done one of 2 ways:

_ProcessesUsageTracker_Add()  ; add a single  process
_ProcessesUsageTracker_AddMultiple()  ; multiple processes in a ProcessList-style array

After the usage tracker object has been created, stats can be collected via one of two calls:

_ProcessUsageTracker_GetUsage()  ; single process - returns a percentage
_ProcessesUsageTracker_GetUsage()  ; multiple Processes - returns an array of %'s

Basically the main loop of the program can be filled with 'GetUsage' calls without juggling anything around.  If a process dies out, an @error code will be returned in the single-process version.  The multiple-process tracker version however lets you retain dead processes in the list although their process handles will be closed.  These can be alternatively cleared up on each call to 'GetUsage' (setting $bRemoveDead to True), or you can opt to clean them up with the following call:

_ProcessesUsageTracker_RemoveDead()  ; Removes any dead processes from the tracker object

Finally, to destroy the trackers and close handles, just call the appropriate function:

_ProcessUsageTracker_Destroy()
_ProcessesUsageTracker_Destroy()

That's about it.  More info is in the headers.

Here's an example of a single process cpu usage tracker:

; ========================================================================================================
; <Process_CPUUsageExample.au3>
;
; Example usage of <Process_CPUUsage.au3>
;
; Author: Ascend4nt
; ========================================================================================================
#include "Process_CPUUsage.au3"

;   --------------------    HOTKEY FUNCTION & VARIABLE --------------------

Global $bHotKeyPressed=False

Func _EscPressed()
    $bHotKeyPressed=True
EndFunc

;   --------------------    MAIN PROGRAM CODE   --------------------

HotKeySet("{Esc}", "_EscPressed")

Local $hSplash, $sSplashText
Local $sProcess, $aProcUsage, $fUsage

; Regular Process:
;~ $sProcess = "firefox.exe"
;~ $sProcess = "sp2004.exe"    ; Stress Prime 2004

; Protected Process (opens a different way):
;~ $sProcess = "audiodg.exe"

; Processes Requiring elevated privilege (will fail even with limited access rights):
;~ $sProcess = "CTAudSvc.exe"

$sProcess = InputBox("Enter Process Name", "Process Name:", "", "", 320, 140)
If @error Or $sProcess = "" Then Exit

$aProcUsage = _ProcessUsageTracker_Create($sProcess)
If @error Then Exit ConsoleWrite("Error calling _ProcessUsageTracker_Create(): " & @error & ", @extended = " & @extended & @CRLF)
Sleep(250)

$hSplash=SplashTextOn("Process CPU Usage Information", "", 360, 20 + 60, Default, Default, 16, Default, 12)

; Start loop
Do
    $sSplashText=""
    $fUsage = _ProcessUsageTracker_GetUsage($aProcUsage)
    If @error Then
        ConsoleWrite("Error from _ProcessUsageTracker_GetUsage(): " & @error & ", @extended = " &@extended & @CRLF)
        ExitLoop
    EndIf
    $sSplashText &= "'"&$sProcess&"' CPU usage: " & $fUsage & " %" & @CRLF
    $sSplashText &= @CRLF & "[Esc] exits"

    ControlSetText($hSplash, "", "[CLASS:Static; INSTANCE:1]", $sSplashText)
    Sleep(500)
Until $bHotKeyPressed

_ProcessUsageTracker_Destroy($aProcUsage)

_

Multiple processes example, which is best used with something like 'chrome' which spawns a number of processes with the same name:

; ========================================================================================================
; <Processes_CPUUsageExample.au3>
;
; Example usage of <Processes_CPUUsage.au3>
;
; Author: Ascend4nt
; ========================================================================================================
#include "Processes_CPUUsage.au3"

;   --------------------    HOTKEY FUNCTION & VARIABLE --------------------

Global $bHotKeyPressed=False

Func _EscPressed()
    $bHotKeyPressed=True
EndFunc

;   --------------------    MAIN PROGRAM CODE   --------------------

HotKeySet("{Esc}", "_EscPressed")

Local $hSplash, $sSplashText
Local $sProcess, $aProcList, $aProcUsage, $aPercents, $nPercents

; Regular Process:
;~ $sProcess = "firefox.exe"
;~ $sProcess = "sp2004.exe"    ; Stress Prime 2004

; Protected Process (opens a different way):
;~ $sProcess = "audiodg.exe"

; Processes Requiring elevated privilege (will fail even with limited access rights):
;~ $sProcess = "CTAudSvc.exe"

$sProcess = InputBox("Enter Process Name", "Process Name:", "", "", 320, 140)
If @error Or $sProcess = "" Then Exit

$aProcUsage = _ProcessesUsageTracker_Create()
_ProcessesUsageTracker_Add($aProcUsage, "sp2004.exe")
_ProcessesUsageTracker_Add($aProcUsage, "CPUStabTest.exe")


$aProcList = ProcessList("chrome.exe")
_ProcessesUsageTracker_AddMultiple($aProcUsage, $aProcList)
_ProcessesUsageTracker_Add($aProcUsage, $sProcess)
_ProcessesUsageTracker_Add($aProcUsage, "audiodg.exe")

Sleep(250)

$hSplash=SplashTextOn("Process CPU Usage Information", "", 380, 24 + 15*2 + $aProcUsage[0][0]*15, Default, Default, 16+4, "Lucida Console", 11)

; Start loop
Do
    ; DEBUG: Interrupt to allow multiple process termination
    ;MsgBox(0, "Next usage", "Next usage time..")
    $sSplashText=""
    $aPercents = _ProcessesUsageTracker_GetUsage($aProcUsage, True)    ; True = Remove dead
    $nPercents = @extended
    If @error Then
        ConsoleWrite("Error from _ProcessesUsageTracker_GetUsage(): " & @error & ", @extended = " &@extended & @CRLF)
        ExitLoop
    EndIf
    For $i = 0 To $nPercents - 1
        $sSplashText &= "'"&$aProcUsage[$i+1][0]&"' [PID #"&$aProcUsage[$i+1][1]&"] CPU usage: " & $aPercents[$i] & " %" & @CRLF
    Next
    $sSplashText &= @CRLF & "[Esc] exits"

    ControlSetText($hSplash, "", "[CLASS:Static; INSTANCE:1]", $sSplashText)

    Sleep(500)
Until $bHotKeyPressed

_ProcessesUsageTracker_Destroy($aProcUsage)

ProcessCPUUsage.zip

  • Like 1

Share this post


Link to post
Share on other sites
chrisT

Very nice, thanks.

How would I be able to monitor "System Idle Process"

Share this post


Link to post
Share on other sites
KLM

Thanks


K L M
------------------
Real Fakenamovich
------------------
K L M
------------------
Real Fakenamovich
------------------

Share this post


Link to post
Share on other sites
Ascend4nt

Very nice, thanks.

How would I be able to monitor "System Idle Process"

 

You can't get a handle to the System Idle process so you can't monitor it using this method.  However, it's simple enough to calculate the Idle time by looking at overall CPU Usage.  Look at my >CPU Multi-Processor Usage UDF - all you need to do is get the overall CPU usage and subtract that from 100 to get the Idle usage.  I'll add a simplified example of this but its easy enough to figure out.

There are however ways of looking directly at the system/idle process CPU usage..

-  One is by making an undocumented call which lists information for all processes and threads - but this is a heavy API call that shouldn't really be used other than for say, a Task Manager.  See _ProcessUDListEverything in my >Process Functions UDFs for an example of this. Basically you'd examine the kernel time of that process

- Another is by using my Performance Counters UDFs which allows you to examine the 'System' and 'Idle' processes CPU usage.  For Idle, you'd use the counter ":2306(Idle)" (Process(Idle)% Processor Time)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • nacerbaaziz
      By nacerbaaziz
      Hello my friends
      I have an inquiry after your permission
      I found a function to get the special line commands for any operation
      It requires the name of the process to be searched
      I want to use it to know the process
      Is this possible with this function
      Here is the code
       
      Func commandLineGet($proc, $strComputer=".")
      dim $array[1]
      local $ArrayNumber
      local $oWMI = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & $strComputer & "\root\cimv2")
      local $oProcessColl = $oWMI.ExecQuery("Select * from Win32_Process where Name= " & '"'& $Proc & '"')
      local $Process
      For $Process In $oProcessColl
      $Process = $Process.Commandline
          ReDim $Array[UBound($Array)+1]
      $ArrayNumber = UBound($Array)-1
      $array[$ArrayNumber] = $Process
      Next
      $ArrayNumber = UBound($Array)-1
      $array[0] = $ArrayNumber
      return $array
      EndFunc
    • simy8891
      By simy8891
      Hi guys,
      It's been a while since I wrote my last message here and a while since I used AutoIt. I'm currently sort of desperate and I'm trying to find some help in regards of getting the network usage per process!
      I'm not interested in the total network usage of the NIC, but only on a specific PID's network utilization. They idea is to collect the amount of traffic uploaded and downloaded by a list of specific processes. So far Process Hacker and Process Explorer are capable of getting what I need, but I need to use these numbers in another script so they're sort of useless to me. I can't seem to find a way around it.
      Any idea, help is greatly appreciated.
      Thanks
    • ur
      By ur
      with the below code, I am keeping waiting for a particular file and waiting in the background.
      While $i <> 10 Sleep(60000) If FileExists(@ScriptDir&"\Binaries.ini") then --some processing-- $i = 10 endif WEnd I thought keeping the Sleep will freeze the process from resources but the CPU being uilized.But it is taking 47%.
      How to free this CPU usage also.?

    • ur
      By ur
      With  ProcessList ( ["name"] )  we are able to get the running process list from the local machine.
       
      Is there anyway to get the list from Remote machine, more precisely to get to know the status whether a particular application is running or not on remote machine using AutoIT?
       
      We can implement through PSList.exe, but again we need to parse the text of it to read the output.
      Is there any direct UDF in AutoIT?
    • Nareshm
      By Nareshm
      If Process exits then end process and ;Some code here {1}
       
      If Process does not exits then ; My {1} Code
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.