Jump to content

Recommended Posts

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

Link to post
Share on other sites
  • 5 weeks later...

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)

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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By t0nZ
      Computer Plucker is a fork and a "restoration" of Computer stats utility by @Rogue5099 (link)
      You can obtain various data about local machine, as from the screenshot.

      But my goal is not (only) to provide another PC stats tool, but to develop a very basic remote inventory tool, like (a small subset of) the abandoned Spiceworks or the Microsoft SCCM.
      So this script can be deployed on a machine as a standalone executable (yes you need only ONE file to distribute) , and launching the .EXE it installs itself to a folder (es. c:\autoit\computerplucker)
      In tools menù you can set two tasks and not only
      one for creating every week a file.ini with all the data of the machine. another one  for creating every week a file.ini with all the data of the machine PLUS uploading a CRYPTED record of the machine in a free mysql DB online For my needs, I am  deploying the .exe and schedule the second task, uploading data one time a week.
      In tools menù you will find also commands for:
      manual creating the .ini data file  to upload the data in crypted records to upload the data in clear text records (for testing..) total uninstall of ComputerPlucker, with a simple security code. many other tasks in not so logical order.. next version I have to tidy the menù... So my plan is to deploy this on my machines, and have the data in a online DB, this DB will be for me only a "cache" for data records to be downloaded (and deleted) by another script.
      As today the account of this TEST DB is embedded in code, using the "File to Base64 String' Code Generator" by @UEZ (used also for embedding icons and XML task definitions)
          Local $mysqlhost = "sql11.freemysqlhosting.net"
          Local $mysqlport = "3306"
          Local $mysqldb = "sql11403701"
          Local $mysqluser = "sql11403701"
          Local $mysqlpsw = "QtL7T9U5GV"
      The DB is one table of 30 mysql tinytext fields... very simple indeed...
      You can try to upload data to this DB and access (phpmyadmin or a random mysql browser app) to see the results.
      Or you can use my ComputerPluckerDBbrowser (see at the end of this post) a script to collect and manage the data.

      PRIVACY warning: you are uploading data of your PC account and PC data, test as your risk (or test in another account...)
       
      I also created a small post in a blog for not so geek friends, and I have a more advanced version of the data browser, you can have more info lookin' here. 😀
      Attached you will find the code, and all the necessary includes are at this >link<.
      ComputerPlucker.EXE is downloadable >HERE<
      ComputerPluckerDBbrowser.EXE is downloadable >HERE<
       
      ComputerPluckerDBbrowser_LITE.au3
       
      ComputerPlucker.au3

    • By DesireDenied
      Hey guys,
      I having some hard times getting false-positive, probably because I am trying to execute my AutoUpdater.
      Here is my code:
       
      Global $iUpdateTimer = 0 While 1 checkUpdates(10) WEnd Func checkUpdates($iDelay = 10) $iDelay = $iDelay * 1000 * 60 If TimerDiff($iUpdateTimer) > $iDelay Then ConsoleWrite('checking for updates...' & @CRLF) $iUpdateTimer = TimerInit() If FileExists('AutoUpdater.exe') Then ShellExecuteWait('AutoUpdater.exe') ; this is the line which cause my problem EndIf EndFunc And AutoUpdater code:
      #include <MsgBoxConstants.au3> #include <FileConstants.au3> Global $sExecName = 'test.exe' Global $sUpdatePath = @UserProfileDir &'\desktop\AnyAppName\update\'& $sExecName Global $sUserPath = @UserProfileDir &'\desktop\AnyAppName\'& $sExecName Global $sCopyright = 'someUniqueStringHere' If Not FileExists($sUpdatePath) Then Exit 0 If FileGetVersion($sUpdatePath, $FV_LEGALCOPYRIGHT) <> $sCopyright Then Exit 0 ; checking if we really want to update and execute the file If FileGetVersion($sUpdatePath) > FileGetVersion($sUserPath) Then $iResponse = MsgBox(BitOR($MB_YESNO, $MB_ICONQUESTION),'AnyAppName', 'There is an update available, would you like to update?') If $iResponse == $IDYES Then If ProcessExists($sExecName) Then ProcessClose($sExecName) Sleep(500) EndIf FileCopy($sUpdatePath, $sUserPath, $FC_OVERWRITE) Sleep(3000) ShellExecute($sUserPath) Exit 1 EndIf EndIf Exit 0 I am not trying to ask, why is my code is getting recognized as false-positive, because this is quite obvious, but is there any other way to get things done without running external process?
       

    • By nacerbaaziz
      hello autoit team
      is there any wey to check if any process run as admin or no?
      i mean e.g if i want to restart any process, now i have the ability to get the process path and commands line
      what i need is a wey to check if the process was runing as admin or no to restart it with the same state.
      here is the part that am using it to restart the process
      func _processRestart($i_pid, $s_ProcessPath) if not (ProcessExists($i_ProcessPid)) then return SetError(1, 0, -1) local $s_ProcessWorkDir = _WinAPI_GetProcessWorkingDirectory($i_ProcessPid) ProcessClose($i_ProcessPid) ProcessWaitClose($i_ProcessPid) ProcessWait(ShellExecute($i_pid,"", $s_ProcessWorkDir)) ProcessesGetList() return true endFunc thanks in advance
    • By Miliardsto
      I want to detect if exact process or window uses directx or opengl or maybe something else library used in applications.
      Thats becouse there could be many windows with same names and different names and the same with process. I got so much process names I want to my script works with all, so i want standardize.
      All of this processes uses DirectX or OpenGL so then If I check this window/process uses these libraries I will be sure thats the right process
    • By TryWare90Days
      I'm trying to kill a malware process, that I can't remove with my www.sophus.com/hom antivirus.

      The malware is known as coinminer,config and my Sophus only creates popups of blocking the malware.

      I know that the malware is constantly launching a svchost *32.exe processes, where the svchost.exe processes are from my Windows 7 operating system.
      I have with no luck tried to do this:
      Global $_bStatus = False
      While $_bStatus = False
                 Global $_iPid
                 Global $_sActiveTitleNew = "svchost *32.exe"
                 $_iPid = WinGetProcess($_sActiveTitleNew)
                 If $_iPid <> -1 Then $_bStatus = ProcessClose($_iPid)   
      Wend
      EXIT
       
      But the $_iPid doesn't ever show anything else than  -1, even if I can see the svchost *32.exe process in my TaskManager
       
      YES - I know I shouldn't EXIT after killing the first malware detection, but it is easier to explain the above for you, so I can get a solution.
×
×
  • Create New...