Jump to content
Sign in to follow this  
Alexxander

Simple script with 30% CPU usage !

Recommended Posts

Alexxander

Hi all

this is a part from my script

#include <Misc.au3>
$dll = DllOpen("user32.dll")

    While 1
    If _IsPressed("31", $dll) Then one()
    If _IsPressed("32", $dll) Then two()
WEnd

Func one()
    MsgBox(0, "", "1")
    While _IsPressed("31") or _IsPressed("61")
        Sleep(1)
    WEnd
EndFunc

Func two()
    MsgBox(0,"", "2")
    While _IsPressed("32") or _IsPressed("62")
        Sleep(1)
    WEnd
EndFunc

it is working fine but it takes 30 % of the CPU usage and it is a small simple script

when i put sleep(100) in the while loop the CPU is 1%

i think that this is a good solution but not for my case cuz the rest of my script really depends on time and 100 msec will matter

can i reduce the CPU usage without using sleep ?

Edited by Alexxander

Share this post


Link to post
Share on other sites
BrewManNH

There's no sleep in your While loop unless you're pressing a key, actually there's no sleeps in any of your while loops unless a key is pressed.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites
mLipok

in HelpFile GUIGetMsg() from latest BETA

 

This function automatically idles the CPU when required so that it can be safely used in tight loops without hogging all the CPU.

 

Try to use this function GUIGetMsg().

  • Like 1

Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2018-03-17

Share this post


Link to post
Share on other sites
BrewManNH

Or don't, and use a sleep like you should, using GUIGetMsg on a script with no GUI is kind of pointless.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

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

    • Sergeant_Shultz
      By Sergeant_Shultz
       How do I setup a Hotkey without using so much of the CPU. There must be a better way.
       
      A.T.
      HotKey Patient History.au3
    • trademaid
      By trademaid
      Im looking to measure cpu usage thats free, and measure cpu usage of a program.
      My goal is to turn intel speed step off under light cpu load.
      I think I can do that, if I can find the cpu usage.
    • rm65453
      By rm65453
      Hi Everyone,
       
      I have been using a script at work for the last 6 months or so. It gets some information from the window title and keeps it in its memory for retrieval. 
       
      currently I am running an infinite loop to look for the window title, the information in the memory is only updated if a few window title is detected.
       
      The trouble with this approach as you can see, is the cpu usage. I was wondering if somehow I can only run this script when a windows change event occurs, otherwise the script stays dormant.
       
      I have no idea how to do that, searched on forum and found some solutions that were years old and did not work for me.
       
      Thanks
    • UEZ
      By UEZ
      AutoIt SysInfo Clock is a small tool in widget style to show the clock, current CPU usage, CPU speed, memory usage and network activity (tcp, ip and udp). Additionally you can use it as an alarm clock. To stop alarm clock tone press the left LED (mail) or wait 60 seconds.
       
      The current CPU usage code is beta and might be not working for some CPUs!

      Main window:

      Move mouse to area below seconds and press rmb to select different color scheme.

      Alarm Clock window:


      Tray menu:



       
      Credits: see scroller (select About).
       
      Special thanks to trancexx for helping me to read out current CPU speed using the WinAPI stuff, AndyG for troubleshooting performance counter issue, czardas for composing "Für Elise" and Ascend4nt for the support!  
       
       
      Download source code + compiled version: Click Me (previous downloads: 1386)
      (Please don't use any download manager!)
       
      Compiled version only: MediaFire.com or 4Shared.com
       

      Coded on Win7 x64 using Aero  / Win8.1 x64 and AutoIt v3.3.12.0.
       
       
      Br,
      UEZ
       
       
      This project is discontinued!
       
       
      Change log:
      v0.9.5.0 build 2013-06-14: initial release
      v0.9.6.0 build 2013-06-15: added _WinAPI_CreateRoundRectRgn() to fix transparency issue on non Aero desktops, small internal modifications and added check for whether performance counters are enabled
      v0.9.6.5 build 2013-06-15: fixed a bug when "Reset Windows Position" was selected twice and color of scroller will fit to clock color schema
      v0.9.8.0 build 2013-06-20: added little music to About part -> many thanks to czardas for mus++ and arranging "Für Elise", added date to clock, replaced CPU usage code -> thanks Ascend4nt
      v0.9.9.0 build 2013-06-21: added 2 more color schemas (mint and purple), added network traffic LED, compiled exe now included in archive
      v0.9.9.0 build 2013-06-22: forgot to increase a variable in ini section
      v0.9.9.0 build 2013-06-24: found also missing modification in context menue after adding two more color schemas
      v0.9.9.0 build 2013-06-26: Ops, forgot to change also radio item proper check in clock color schema sub menu
      v0.9.9.1 build 2013-06-27: added option to select whether SysInfo Clock should start at windows startup
      v0.9.9.2 build 2013-07-01: added yellow-red mark to the small info indicators and additional info when hovering about the small indicators, small internal changes
      v0.9.9.5 build 2013-07-05: added features: singleton, update check, visit web site, bring GUI to front and fixed some smaller bugs + some internal changes
      v0.9.9.6 build 2013-07-11: added alarm clock feature
      v0.9.9.7 build 2014-06-23: adapted code to run on AutoIt version 3.3.12.0
      v0.9.9.7 build 2014-08-27: some internal "cosmetic" changes -> this project is discontinued!
    • Ascend4nt
      By Ascend4nt
      CPU Multi-Processor Usage

      This is an example of getting and displaying processor usage for all processors in a system.  It uses the 'undocumented' NtQuerySystemInformation function to gather processor usage information and then does calculations based on the delta of two readings.  I wrote this as an alternative to using my >Performance Counters UDF - specifically, check out >Example # 4: System CPU Usage (by Processor).
      There is now a new interface, as well as two ways to track CPU usage. The first method tracks usage for all CPU's, and additionally produces an overall CPU usage result.  The second method tracks Overall CPU usage - a combined value representing all cores as one unit.  Note that this second method uses GetSystemTimes, which requires Windows XP SP1 or higher.
      The usage works like this for all CPU's:
      $aCPUsUsageTracker = _CPUsUsageTracker_Create() $iTotalCPUs = $aCPUsUsageTracker[0][0] ; Call the following repeatedly - $aCPUsUsageTracker will be updated automatically: $aPercents = _CPUsUsageTracker_GetUsage($aCPUsUsageTracker) For Overall CPU usage, either look at $aPercents[$iTotalCPUs] above, or use this interface (reliant on GetSystemTimes):
      $aCPUOverallTracker = _CPUOverallUsageTracker_Create() ; Call the following repeatedly - $aCPUOverallTracker will be updated automatically: $fUsage = _CPUOverallUsageTracker_GetUsage($aCPUOverallTracker) _
      Need to see how CPU usage is affected? A simple tool I use to stress-test individual CPU cores is Stress Prime 2004, which can be run multiple times.
       
      P.S. All I ask is that you acknowledge me in some way if you use any of this code.
      updates:
      2013-08-31:
      - Added a simple Overall and Idle CPU usage example
      2013-06-18:
      - Changed interface for getting CPU usage. Now there's no need to juggle arrays around
      [obsolete version]:
      - fixed bound check in _CPUCalculateUsages() to look at 2nd dimension
      CPU_ProcessorUsage.au3  (prev downloads: ~15)
      ; ======================================================================================================== ; <CPU_ProcessorUsage.au3> ; ; Example of an alternative means to read individual CPU Usages for multiple CPUs, ; along with the combined overall CPU usage. (Alternative to Performance Counters) ;  Readings are shown in a 'Splash' window ; ; Functions: ;    _CPUGetTotalProcessorTimes()      ; Gets Overall (combined CPUs) Processor Times ;    _CPUGetIndividualProcessorTimes() ; Returns an array of CPU usage info for individual processors ;    _CPUsUsageTracker_Create()        ; Creates a CPU usage tracker for all CPUs ;    _CPUsUsageTracker_GetUsage()      ; Updates CPU usage tracker and returns a CPU usage array ;    _CPUOverallUsageTracker_Create()  ; Creates a CPU usage tracker for Overall CPU usage ;    _CPUOverallUsageTracker_GetUsage(); Updates CPU usage tracker and returns CPU usage [Overall Usage] ; ; See also: ;    Performance Counters UDF ; ; ; Author: Ascend4nt ; ======================================================================================================== ;   --------------------    HOTKEY FUNCTION & VARIABLE -------------------- Global $bHotKeyPressed=False Func _EscPressed()     $bHotKeyPressed=True EndFunc ; ============================================================================================== ; Func _CPUGetTotalProcessorTimes() ; ; Gets the total (combined CPUs) system processor times (as FILETIME) ; Note that Kernel Mode time includes Idle Mode time, so a proper calculation of usage time is ;   Kernel + User - Idle ; And percentage (based on two readings): ;  (Kernel_b - Kernel_a) + (User_b - User_a) - (Idle_b - Idle_a) * 100 ;    / (Kernel_b - Kernal_a) + (User_b - User_a) ; ; O/S Requirements: min. Windows XP SP1+ ; ; Returns: ;  Success: Array of info for total (combined CPU's) processor times: ;   [0] = Idle Mode Time ;   [1] = Kernel Mode Time -> NOTE This INCLUDES Idle Time ;   [2] = User Mode Time ; ;  Failure: "" with @error set: ;     @error = 2: DLLCall error, @extended = error returned from DLLCall ;    @error = 3: API call returned False - call GetLastError for more info ; ; Author: Ascend4nt ; ============================================================================================== Func _CPUGetTotalProcessorTimes()     Local $aRet, $stSystemTimes     $stSystemTimes = DllStructCreate("int64 IdleTime;int64 KernelTime;int64 UserTime;")     $aRet = DllCall("kernel32.dll", "bool", "GetSystemTimes", "ptr", DllStructGetPtr($stSystemTimes, 1), _         "ptr", DllStructGetPtr($stSystemTimes, 2), "ptr", DllStructGetPtr($stSystemTimes, 3) )     If @error Then Return SetError(2, @error, "")     If Not $aRet[0] Then Return SetError(3, 0, "")     Dim $aRet[3] = [ _         DllStructGetData($stSystemTimes, 1), _         DllStructGetData($stSystemTimes, 2), _         DllStructGetData($stSystemTimes, 3) ]     Return $aRet EndFunc ; ============================================================================================== ; Func _CPUGetIndividualProcessorTimes() ; ; Gets an array of system processor times (as FILETIME) ; Note that Kernel Mode time includes Idle Mode time, so a proper calculation of usage time is ;   Kernel + User - Idle ; And percentage (based on two readings): ;  (Kernel_b - Kernel_a) + (User_b - User_a) - (Idle_b - Idle_a) * 100 ;    / (Kernel_b - Kernal_a) + (User_b - User_a) ; ; Returns: ;  Success: 2 Dimensional Array of info [@extended = #of CPU's]: ;   [0][0] = # of CPUs (and array elements) ;   [1..n][0] = Idle Mode Time for CPU # n ;   [1..n][1] = Kernel Mode Time for CPU # n -> NOTE This INCLUDES Idle Time ;   [1..n][2] = User Mode Time for CPU # n ; ;  Failure: "" with @error set: ;     @error = 2: DLLCall error, @extended = error returned from DLLCall ;    @error = 3: NTSTATUS returned error code, @extended contains error code ;    @error = 4: Invalid length returned, @extended is length ; ; Author: Ascend4nt ; ============================================================================================== Func _CPUGetIndividualProcessorTimes()     ; DPC = Deferred Procedure Calls     Local $tagSYSTEM_PROCESSOR_TIMES = "int64 IdleTime;int64 KernelTime;int64 UserTime;int64 DpcTime;int64 InterruptTime;ulong InterruptCount;"     Local $aRet, $stProcessorTimes, $stBuffer     Local $i, $nTotalCPUStructs, $pStructPtr     ; 256 [maximum CPU's] * 48 (structure size) = 12288     $stBuffer = DllStructCreate("byte Buffer[12288];")     ; SystemProcessorTimes = 8     Local $aRet=DllCall("ntdll.dll", "long", "NtQuerySystemInformation", "int", 8, "ptr", DllStructGetPtr($stBuffer), "ulong", 12288, "ulong*", 0)     If @error Then Return SetError(2, @error, "")     ; NTSTATUS of something OTHER than success?     If $aRet[0] Then Return SetError(3, $aRet[0], "")     ; Length invalid?     If $aRet[4] = 0 Or $aRet[0] > 12288 Or Mod($aRet[4], 48) <> 0 Then Return SetError(4, $aRet[4], "")     $nTotalCPUStructs = $aRet[4] / 48 ;~     ConsoleWrite("Returned buffer length = " & $aRet[4] & ", len/48 (struct size) = "& $nTotalCPUStructs & @CRLF)     ; We are interested in Idle, Kernel, and User Times (3)     Dim $aRet[$nTotalCPUStructs + 1][3]     $aRet[0][0] = $nTotalCPUStructs     ; Traversal Pointer for individual CPU structs     $pStructPtr = DllStructGetPtr($stBuffer)     For $i = 1 To $nTotalCPUStructs         $stProcessorTimes = DllStructCreate($tagSYSTEM_PROCESSOR_TIMES, $pStructPtr)         $aRet[$i][0] = DllStructGetData($stProcessorTimes, "IdleTime")         $aRet[$i][1] = DllStructGetData($stProcessorTimes, "KernelTime")         $aRet[$i][2] = DllStructGetData($stProcessorTimes, "UserTime")         ; Next CPU structure         $pStructPtr += 48     Next     Return SetExtended($nTotalCPUStructs, $aRet) EndFunc ; ============================================================================================== ; Func _CPUsUsageTracker_Create() ; ; Creates a CPU usage tracker array for all processors.  This array should be passed ; to _CPUsUsageTracker_GetUsage() to get current usage information back. ; ; Returns: ;  Success: An array used to track CPU usage [@extended = # of CPU's] ;   Array 'internal' format: ;      $arr[0][0] = # of CPU's ;      $arr[1..n][0] = Total CPU Time (Kernel + User Mode) ;      $arr[1..n][1] = Total Active CPU Time (Kernel + User - Idle) ; ;  Failure: "" with @error set [reflects _CPUGetIndividualProcessorTimes codes]: ;     @error = 2: DLLCall error, @extended = error returned from DLLCall ;    @error = 3: NTSTATUS returned error code, @extended contains error code ;    @error = 4: Invalid length returned, @extended is length ; ; Author: Ascend4nt ; ============================================================================================== Func _CPUsUsageTracker_Create()     Local $nTotalCPUs, $aCPUTimes, $aCPUsUsage     $aCPUTimes = _CPUGetIndividualProcessorTimes()     If @error Then Return SetError(@error, @extended, "")     $nTotalCPUs = @extended     Dim $aCPUsUsage[$nTotalCPUs + 1][2]     $aCPUsUsage[0][0] = $nTotalCPUs     For $i = 1 To $nTotalCPUs         ; Total         $aCPUsUsage[$i][0] = $aCPUTimes[$i][1] + $aCPUTimes[$i][2]         ; TotalActive (Kernel Time includes Idle time, so we need to subtract that)         $aCPUsUsage[$i][1] = $aCPUTimes[$i][1] + $aCPUTimes[$i][2] - $aCPUTimes[$i][0]     Next     Return SetExtended($nTotalCPUs, $aCPUsUsage) EndFunc ; ============================================================================================== ; Func _CPUOverallUsageTracker_Create() ; ; Creates a CPU usage tracker array for Overall combined processors usage. ; This array should be passed to _CPUOverallUsageTracker_GetUsage() to get ; current usage information. ; ; Returns: ;  Success: An array used to track Overall CPU usage ;   Array 'internal' format: ;      $arr[0] = Total Overall CPU Time (Kernel + User Mode) ;      $arr[1] = Total Active Overall CPU Time (Kernel + User - Idle) ; ;  Failure: "" with @error set [reflects _CPUGetTotalProcessorTimes codes]: ;     @error = 2: DLLCall error, @extended = error returned from DLLCall ;    @error = 3: API call returned False - call GetLastError for more info ; ; Author: Ascend4nt ; ============================================================================================== Func _CPUOverallUsageTracker_Create()     Local $aCPUTimes, $aCPUsUsage[2]     $aCPUTimes = _CPUGetTotalProcessorTimes()     If @error Then Return SetError(@error, @extended, "")     ; Total     $aCPUsUsage[0] = $aCPUTimes[1] + $aCPUTimes[2]     ; TotalActive (Kernel Time includes Idle time, so we need to subtract that)     $aCPUsUsage[1] = $aCPUTimes[1] + $aCPUTimes[2] - $aCPUTimes[0]     Return $aCPUsUsage EndFunc ; ============================================================================================== ; Func _CPUsUsageTracker_GetUsage(ByRef $aCPUsUsage) ; ; Updates a CPUsUsage array and returns an array of CPU Usage information for all processors. ; ; Returns: ;  Success: Array of CPU Usage -> 1 for each processor + 1 for Overall [@extended = # of processors] ;    [0..n]  = CPU Usage (Percentage) ;   [#CPUs] = CPUs Overall Usage (Percentage) ;  Failure: "" with @error set to 1 for invalid parameters, or: ;     @error = 2: DLLCall error, @extended = error returned from DLLCall ;    @error = 3: NTSTATUS returned error code, @extended contains error code ;    @error = 4: Invalid length returned, @extended is length ; ; Author: Ascend4nt ; ============================================================================================== Func _CPUsUsageTracker_GetUsage(ByRef $aCPUsUsage)     If Not IsArray($aCPUsUsage) Or UBound($aCPUsUsage, 2) < 2 Then Return SetError(1, 0, "")     Local $nTotalCPUs, $aUsage, $aCPUsCurInfo     Local $nTotalActive, $nTotal     Local $nOverallActive, $nOverallTotal     $aCPUsCurInfo = _CPUsUsageTracker_Create()     If @error Then Return SetError(@error, @extended, "")     $nTotalCPUs = $aCPUsCurInfo[0][0]     Dim $aUsage[$nTotalCPUs + 1]     $nOverallActive = 0     $nOverallTotal = 0     For $i = 1 To $nTotalCPUs         $nTotal = $aCPUsCurInfo[$i][0] - $aCPUsUsage[$i][0]         $nTotalActive = $aCPUsCurInfo[$i][1] - $aCPUsUsage[$i][1]         $aUsage[$i - 1] = Round($nTotalActive * 100 / $nTotal, 1)         $nOverallActive += $nTotalActive         $nOverallTotal += $nTotal     Next     $aUsage[$nTotalCPUs] = Round( ($nOverallActive / $nTotalCPUs) * 100 / ($nOverallTotal / $nTotalCPUs), 1)     ; Replace current usage tracker info     $aCPUsUsage = $aCPUsCurInfo     Return SetExtended($nTotalCPUs, $aUsage) EndFunc ; ============================================================================================== ; Func _CPUOverallUsageTracker_GetUsage(ByRef $aCPUsUsage) ; ; Updates a CPUsUsage array and returns CPU Usage information [Overall processor usage] ; ; Returns: ;  Success: CPU Usage (Percentage) ;  Failure: 0 with @error set to 1 for invalid parameters, or: ;     @error = 2: DLLCall error, @extended = error returned from DLLCall ;    @error = 3: API call returned False - call GetLastError for more info ; ; Author: Ascend4nt ; ============================================================================================== Func _CPUOverallUsageTracker_GetUsage(ByRef $aCPUsUsage)     If Not IsArray($aCPUsUsage) Or UBound($aCPUsUsage) < 2 Then Return SetError(1, 0, "")     Local $aCPUsCurInfo, $fUsage, $nTotalActive, $nTotal     $aCPUsCurInfo = _CPUOverallUsageTracker_Create()     If @error Then Return SetError(@error, @extended, 0)     $nTotal = $aCPUsCurInfo[0] - $aCPUsUsage[0]     $nTotalActive = $aCPUsCurInfo[1] - $aCPUsUsage[1]     ; Replace current usage tracker info     $aCPUsUsage = $aCPUsCurInfo     Return Round($nTotalActive * 100 / $nTotal, 1) EndFunc ;   --------------------    MAIN PROGRAM CODE   -------------------- HotKeySet("{Esc}", "_EscPressed") Local $hSplash, $sSplashText ; CPU Usage for all CPU's Local $iTotalCPUs, $aCPUsUsageTracker, $aPercents ; Overall CPU Usage Tracker        ; (GetSystemTimes) ;~ Local $aCPUOverallTracker ; CPUs Usage Tracker $aCPUsUsageTracker = _CPUsUsageTracker_Create() If @error Then Exit ConsoleWrite("Error calling _CPUsUsageTracker_Create():" & @error & ", @extended = " & @extended & @CRLF) ; Overall CPU Usage tracker ;~ $aCPUOverallTracker = _CPUOverallUsageTracker_Create() ;~ If @error Then Exit ConsoleWrite("Error calling _CPUOverallUsageTracker_Create():" & @error & ", @extended = " & @extended & @CRLF) $iTotalCPUs = $aCPUsUsageTracker[0][0] ConsoleWrite("Total # CPU's: " & $iTotalCPUs & @CRLF) Sleep(250) $hSplash=SplashTextOn("CPU Usage Information [" & $iTotalCPUs & " total CPU's]", "", _     240, 20 + ($iTotalCPUs + 1) * 35, Default, Default, 16, Default, 12) ; Start loop Do     $aPercents = _CPUsUsageTracker_GetUsage($aCPUsUsageTracker)     $sSplashText=""     For $i=0 To $iTotalCPUs - 1         $sSplashText &= "CPU #"& $i+1 & ": " & $aPercents[$i] & " %" & @CRLF     Next     $sSplashText &= @CRLF &"[Overall CPU Usage] :" & $aPercents[$iTotalCPUs] & " %" & @CRLF     ; Alternative, if all we wanted was Overall CPU Usage: ;~     $sSplashText &= @CRLF &"[Overall CPU Usage] :" & _CPUOverallUsageTracker_GetUsage($aCPUOverallTracker) & " %" & @CRLF     $sSplashText &= @CRLF & "[Esc] exits"     ControlSetText($hSplash, "", "[CLASS:Static; INSTANCE:1]", $sSplashText)     Sleep(500) Until $bHotKeyPressed _
      Overall CPU Usage (and Idle calculation) example:
      ; ======================================================================================================== ; <CPU_ProcessorUsageOverall.au3> ; ; Example of reading combined overall CPU usage and deducing Idle CPU usage as well ;  Readings are shown in a 'Splash' window ; ; Functions: ;    _CPUGetTotalProcessorTimes()      ; Gets Overall (combined CPUs) Processor Times ;    _CPUOverallUsageTracker_Create()  ; Creates a CPU usage tracker for Overall CPU usage ;    _CPUOverallUsageTracker_GetUsage(); Updates CPU usage tracker and returns CPU usage [Overall Usage] ; ; External Functions: ;    _CPUGetIndividualProcessorTimes() ; Returns an array of CPU usage info for individual processors ;    _CPUsUsageTracker_Create()        ; Creates a CPU usage tracker for all CPUs ;    _CPUsUsageTracker_GetUsage()      ; Updates CPU usage tracker and returns a CPU usage array ; ; See also: ;    <CPU_ProcessorUsage.au3>    ; Individual CPU processor usage example ;    Performance Counters UDF ; ; ; Author: Ascend4nt ; ======================================================================================================== ; --- UDF's --- ; ============================================================================================== ; Func _CPUGetTotalProcessorTimes() ; ; Gets the total (combined CPUs) system processor times (as FILETIME) ; Note that Kernel Mode time includes Idle Mode time, so a proper calculation of usage time is ;   Kernel + User - Idle ; And percentage (based on two readings): ;  (Kernel_b - Kernel_a) + (User_b - User_a) - (Idle_b - Idle_a) * 100 ;    / (Kernel_b - Kernal_a) + (User_b - User_a) ; ; O/S Requirements: min. Windows XP SP1+ ; ; Returns: ;  Success: Array of info for total (combined CPU's) processor times: ;   [0] = Idle Mode Time ;   [1] = Kernel Mode Time -> NOTE This INCLUDES Idle Time ;   [2] = User Mode Time ; ;  Failure: "" with @error set: ;     @error = 2: DLLCall error, @extended = error returned from DLLCall ;    @error = 3: API call returned False - call GetLastError for more info ; ; Author: Ascend4nt ; ============================================================================================== Func _CPUGetTotalProcessorTimes()     Local $aRet, $aTimes     $aRet = DllCall("kernel32.dll", "bool", "GetSystemTimes", "uint64*", 0, "uint64*", 0, "uint64*", 0)     If @error Then Return SetError(2, @error, "")     If Not $aRet[0] Then Return SetError(3, 0, "")     Dim $aTimes[3] = [ $aRet[1], $aRet[2], $aRet[3] ]     Return $aTimes EndFunc ; ============================================================================================== ; Func _CPUOverallUsageTracker_Create() ; ; Creates a CPU usage tracker array for Overall combined processors usage. ; This array should be passed to _CPUOverallUsageTracker_GetUsage() to get ; current usage information. ; ; Returns: ;  Success: An array used to track Overall CPU usage ;   Array 'internal' format: ;      $arr[0] = Total Overall CPU Time (Kernel + User Mode) ;      $arr[1] = Total Active Overall CPU Time (Kernel + User - Idle) ; ;  Failure: "" with @error set [reflects _CPUGetTotalProcessorTimes codes]: ;     @error = 2: DLLCall error, @extended = error returned from DLLCall ;    @error = 3: API call returned False - call GetLastError for more info ; ; Author: Ascend4nt ; ============================================================================================== Func _CPUOverallUsageTracker_Create()     Local $aCPUTimes, $aCPUsUsage[2]     $aCPUTimes = _CPUGetTotalProcessorTimes()     If @error Then Return SetError(@error, @extended, "")     ; Total     $aCPUsUsage[0] = $aCPUTimes[1] + $aCPUTimes[2]     ; TotalActive (Kernel Time includes Idle time, so we need to subtract that)     $aCPUsUsage[1] = $aCPUTimes[1] + $aCPUTimes[2] - $aCPUTimes[0]     Return $aCPUsUsage EndFunc ; ============================================================================================== ; Func _CPUOverallUsageTracker_GetUsage(ByRef $aCPUsUsage) ; ; Updates a CPUsUsage array and returns CPU Usage information [Overall processor usage] ; ; Returns: ;  Success: CPU Usage (Percentage) ;  Failure: 0 with @error set to 1 for invalid parameters, or: ;     @error = 2: DLLCall error, @extended = error returned from DLLCall ;    @error = 3: API call returned False - call GetLastError for more info ; ; Author: Ascend4nt ; ============================================================================================== Func _CPUOverallUsageTracker_GetUsage(ByRef $aCPUsUsage)     If Not IsArray($aCPUsUsage) Or UBound($aCPUsUsage) < 2 Then Return SetError(1, 0, "")     Local $aCPUsCurInfo, $fUsage, $nTotalActive, $nTotal     $aCPUsCurInfo = _CPUOverallUsageTracker_Create()     If @error Then Return SetError(@error, @extended, 0)     $nTotal = $aCPUsCurInfo[0] - $aCPUsUsage[0]     $nTotalActive = $aCPUsCurInfo[1] - $aCPUsUsage[1]     ; Replace current usage tracker info     $aCPUsUsage = $aCPUsCurInfo     Return Round($nTotalActive * 100 / $nTotal, 1) EndFunc ;   --------------------    HOTKEY FUNCTION & VARIABLE -------------------- Global $bHotKeyPressed=False Func _EscPressed()     $bHotKeyPressed=True EndFunc ;   --------------------    MAIN PROGRAM CODE   -------------------- HotKeySet("{Esc}", "_EscPressed") Local $hSplash, $sSplashText ; Overall CPU Usage Tracker        ; (GetSystemTimes) Local $aCPUOverallTracker, $fPercent ; Overall CPU Usage tracker $aCPUOverallTracker = _CPUOverallUsageTracker_Create() If @error Then Exit ConsoleWrite("Error calling _CPUOverallUsageTracker_Create():" & @error & ", @extended = " & @extended & @CRLF) Sleep(250) $hSplash=SplashTextOn("CPU [Overall] Usage Information", "", _     240, 100, Default, Default, 16, Default, 12) ; Start loop Do     $fPercent = _CPUOverallUsageTracker_GetUsage($aCPUOverallTracker)     $sSplashText=""     $sSplashText &= "[Overall CPU Usage] :" & $fPercent & " %" & @CRLF     $sSplashText &= "[Idle] : " & (100 - $fPercent) & " %" & @CRLF     $sSplashText &= @CRLF & "[Esc] exits"     ControlSetText($hSplash, "", "[CLASS:Static; INSTANCE:1]", $sSplashText)     Sleep(500) Until $bHotKeyPressed CPU_ProcessorUsageOverall.au3
×