InternetMonkeyBoy

Super Idle Down Process

14 posts in this topic

Hello.  I need a trick to make a process idle down less than sleep.  I use onevents for almost everything, but the problem is the project I'm working on has almost 50 processes.

Even at around 1% idle it adds up and there will be more processes added.  What I'm looking to do is get to a C like idle of .03 to .08 cpu.  Any tricks you have will be great and I will post the final code I use.  I love AutoIt, but is does need a cooler name, lol.  Thx.

Share this post


Link to post
Share on other sites



InternetMonkeyBoy,

How about this code?

And as for "cool" names - "pot to kettle, over"!

M23


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

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Almost done.  Thank you Melba23 very much for pointing me in the right direction.  Been hitting MSDN and others but a few more tweaks and I'll post it late tonight.

_supersleep() will bring your CPU on a preocess to .01 to .02 but normally 00.0000 (nothing)

Next I will tweak the AutoIt (whatever it hooks into) and cool it down.

This thing is really for developers running many many processes that NEED it to be super perty - that need the proces to be running all the time but like a zombie .

Please post any tricks for cooling a process by turning off non onevent stuff.  and thx.

I think I'll change the name to _sleeplikeazombie() (kidding)

Share this post


Link to post
Share on other sites

IMB,

When I run this on my machine

while 1
    sleep(100)
wend

it uses 0.02 CPU as reported by Process Explorer.  Perhaps I am missing your point.

If I wanted to slow down a set of processes I think I would look at changing their dispatching priority.

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

Well, I've tried all these things and combos of them.  This thing re-spawns the same exe with different tasks.  Simple sleep doesn't put the process down enough.  IMB your machine must be very very fast.  Execute 500 of those Sleep(100) processes and add it up and you'll see what I',m getting.   I've found many DLL calls but not do it just the way I need it done.   Anyways, it may not seem like such a big deal but when your doing this kind of thing is turns into a big deal. 

I'll crack it sooner or later and then someone will post some odd DLL call that does it better.

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

On 8/6/2016 at 3:12 AM, InternetMonkeyBoy said:

Execute 500 of those Sleep(100) processes and add it up and you'll see what I',m getting.

#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

#include "MailSlot.au3" ; https://www.autoitscript.com/forum/topic/106710-mailslot/

Global $sMailSlotName = "\\.\mailslot\RandomNameForThisTest\" & @AutoItPID
Global $hMailSlot = 0

Global $hDll_ntdll = DllOpen("ntdll.dll")

If $CmdLine[0] = 0 Then WatcherGui()
If $CmdLine[0] > 2 Then
    If $CmdLine[3] = "/RunSleepTest" Then
        RunSleepTest__HPSleep()
    EndIf
EndIf
Exit

Func WatcherGui()

    $hMailSlot = _MailSlotCreate($sMailSlotName)
    If @error Then
        MsgBox(48 + 262144, "MailSlot", "Failed to create new account!" & @CRLF & "Probably one using that 'address' already exists.")
        Exit
    EndIf

    #Region ### START Koda GUI section ### Form=
    Local $Form1 = GUICreate("Form1", 623, 449, 192, 114, -1, BitOR($WS_EX_TOPMOST, $WS_EX_WINDOWEDGE))
    Local $ButtonRunEm = GUICtrlCreateButton("Run 'em", 536, 12, 75, 25)
    Local $ButtonKillEm = GUICtrlCreateButton("Say bye", 536, 48, 75, 25)
    Local $ButtonSayHello = GUICtrlCreateButton("Say Hello", 536, 48 + 34, 75, 25)
    Local $Edit1 = GUICtrlCreateEdit("", 8, 8, 513, 429)
    GUICtrlSetData(-1, "Edit1")
    GUISetState(@SW_SHOW)
    #EndRegion ### END Koda GUI section ###
    GUICtrlSetState($ButtonKillEm, $GUI_DISABLE)
    GUICtrlSetState($ButtonSayHello, $GUI_DISABLE)
    Local $nMsg, $n, $t, $s, $a[11]
    $a[0] = UBound($a) - 1
    While 1
        $nMsg = GUIGetMsg()
        Switch $nMsg
            Case $GUI_EVENT_CLOSE
                GUIDelete($Form1)
                While WinExists("RunSleepTest hidden GUI")
                    ToolTip("kill them rouge processes, kill 'em all !!!")
                    WinClose("RunSleepTest hidden GUI")
                WEnd
                Exit

            Case $ButtonRunEm
                GUICtrlSetState($ButtonRunEm, $GUI_DISABLE)
                $t = TimerInit()
                $s = ""
                For $n = 1 To $a[0]
                    $a[$n] = Run('"' & @AutoItExe & '" "' & @ScriptFullPath & '" ' & @AutoItPID & ' ' & $n & ' /RunSleepTest')
                    $s &= 'Runing on PID ' & $a[$n] & @CRLF
                Next
                GUICtrlSetData($Edit1, $s & @CRLF & ' loaded in ' & Round(TimerDiff($t)) & ' mSec')
                GUICtrlSetData($Edit1, @CRLF, 1)

                GUICtrlSetState($ButtonKillEm, $GUI_ENABLE)
                GUICtrlSetState($ButtonSayHello, $GUI_ENABLE)

            Case $ButtonKillEm
                GUICtrlSetState($ButtonKillEm, $GUI_DISABLE)
                GUICtrlSetState($ButtonSayHello, $GUI_DISABLE)
                For $n = 1 To $a[0]
                    _MailSlotWrite("\\.\mailslot\RandomNameForThisTest\" & $a[$n], "good bye baby")
                Next
                GUICtrlSetState($ButtonRunEm, $GUI_ENABLE)

            Case $ButtonSayHello
                $t = TimerInit()
                For $n = 1 To $a[0]
                    _MailSlotWrite("\\.\mailslot\RandomNameForThisTest\" & $a[$n], "hello there")
                Next
                GUICtrlSetData($Edit1, ' an order of ' & $a[0] & ' hello''s took' & Round(TimerDiff($t), 4) & ' mSec' & @CRLF, 1)
        EndSwitch
    WEnd

EndFunc   ;==>WatcherGui

Func RunSleepTest__HPSleep()

    Local $hMailSlot = _MailSlotCreate($sMailSlotName)
    If @error Then
        MsgBox(48 + 262144, "MailSlot", "Failed to create new account!" & @CRLF & "Probably one using that 'address' already exists.")
        Exit
    EndIf
    AutoItWinSetTitle("RunSleepTest hidden GUI " & @AutoItPID)

    Local $iSize, $i, $n, $c = 0, $d = 0
    For $n = 1 To Int($CmdLine[2])
        $c += 1
        If $c * 45 > @DesktopHeight - 100 Then
            $c = 1
            $d += 1
        EndIf
    Next

    While 1

;~      _HPSleep(20) ;  would this be better
        Sleep(20) ;     than this ???

        $iSize = _MailSlotCheckForNextMessage($hMailSlot)
        If $iSize Then
            Local $sData = _MailSlotRead($hMailSlot, $iSize, 2)
            ToolTip(@HOUR & ":" & @MIN & ":" & @SEC & "." & @MSEC & @CR & $sData, ($d * 120) + @SEC, ($c * 45) + @SEC, "fork on PID " & @AutoItPID)
            Sleep(2000)
            ToolTip("")
;~          MsgBox(0, @AutoItPID, @HOUR & ":" & @MIN & ":" & @SEC & "." & @MSEC & @CR & $sData, 1)
            If StringInStr($sData, "good bye baby") Then Exit
        EndIf
    WEnd
EndFunc   ;==>RunSleepTest__HPSleep

Func _HPSleep($iSleep, $fMs = 1) ;, $highPrecision = 0)
    ; default is milliseconds, otherwise microseconds (1 ms = 1000 µs)
    ; $highPrecision should be 0 or 1
    If $fMs Then $iSleep *= 1000 ; convert to ms
;~     if $highPrecision > 0 Then DllCall($hDll_winmm, "int", "timeBeginPeriod", "int", $highPrecision)
    DllCall($hDll_ntdll, "dword", "NtDelayExecution", "int", 0, "int64*", -10 * $iSleep)
;~     if $highPrecision > 0 Then DllCall($hDll_winmm, "int", "timeEndPeriod", "int", $highPrecision)
    ;
    ; https://www.autoitscript.com/forum/topic/77905-sleep-down-to-100-nano-seconds/?do=findComment&comment=1067220
    ; A word of caution, directly from Microsoft, http://msdn.microsoft.com/en-us/library/windows/desktop/dd757624(v=vs.85).aspx
    ;
EndFunc   ;==>_HPSleep

I'm curious, so I did :) 
Not much of a difference, _HPSleep() looks better but uses more memory and I don't know what is the aftermath of constant usage ( due to lack for experience ).
Since I have no clue of what real life use you need to solve, maybe using a ram disk would help ?

Regards

Edited by argumentum

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

Your are right - your code works like I want mine to work.   That's not my code though.   I've gone through MSDN and any others I could find and I think I've got it work work.  Kind of.   I will post it today or so.   The big difference is the size and what it is doing.

I'll make at least two examples for you to check out.

Once I've got this thing done there's another piece that I'll make to cool down a process that is up with a gui but needs to be very quite.  I get that this seems like I'm running after tiny things but it isn't.  It's very important because almost everything that goes through the project I'm working on will be prototyped in a clipper like AutoIt language.  They are very much a like.  This code will carry through to C/++, ASM, and even to JAVA (Android)

 

PS- Melba may I include a link to my Software in a post?   Should someone want to see what its being used in.  I will not do that unless you say ok.  thx.

 

Edited by InternetMonkeyBoy

Share this post


Link to post
Share on other sites

InternetMonkeyBoy,

Quote

may I include a link to my Software in a post? 

As long as it is not payware nor infringes the Forum rules in any way, then there is no problem at all.

M23

 


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

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Here's a supersleep.  It's very simple and I've found many DLL calls that work as well.  Use with care because your script is dead for the ms you tell it.

On my machines which are slow a process at idle with no GUI can tap 1 to 2 percent CPU.  This gives you ZERO CPU usage.

The way I'm using it is when there is no GUI up I call it several times...

supersleep(250)

supersleep(250

supersleep(250)

supersleep(250)

which bring my process CPU to zero but still allows onevent stuff to work fine.  I'm also finding it useful to pepper my code with it.  Cooling down processes that do not have to be in such a hurry.

 

More to come... Thx Melba.  I'll put a link up later after my next update.  I don't think it violates the forum rules but I think you might want to look at it first.

 

Func supersleep($ms)
    $ms = $ms * -10000
    Local Static $dll = DllOpen("ntdll.dll")
    Local $struct = DllStructCreate("int64 time;")
    DllStructSetData($struct, "time", $ms)
    DllCall($dll, "dword", "ZwDelayExecution", "int", 0, "ptr", DllStructGetPtr($struct))
EndFunc   ;==>_supersleep

 

Share this post


Link to post
Share on other sites

Do you mean "NtDelayExecution" instead of "ZwDelayExecution"?   Seems to have to same effect.

Also once a call has been made to ntddll.dll it appears you do not even need static or global >> a simpel local works just the same.

 

1 person likes this

Share this post


Link to post
Share on other sites

Ok, so here's the final (so far) for supersleep():

 

Func supersleep($ms)
    $ms = $ms * -10000
    Local $dll = DllOpen("ntdll.dll")
    Local $struct = DllStructCreate("int64 time;")
    DllStructSetData($struct, "time", $ms)
    DllCall($dll, "dword", "ZwDelayExecution", "int", 0, "ptr", DllStructGetPtr($struct))
EndFunc   ;==>supersleep

 

I removed the static from the $dll handle open.  Turns out the DLL handles it all just fine.  Also, you do not even have to release the resource.  Your program will do it when it ends.   There is no memory bleed at all.  Use this wisely.  Strong mojo here.  GL.

 

 

 

 

 

Share this post


Link to post
Share on other sites

InternetMonkeyBoy,

it might well work but you are continually opening the DLL, which will slow down the script as the variable namespace is created each time and it might well pose problems elsewhere. Some, if not all, DLLs maintain an internal reference count of the number of times they have been opened so that they remain in memory until no longer required - which is when you need to use DLLClose to free the memory (a good example is _IsPressed, look in the Help file to see the recommendation).

Using Static means you only open the DLL once and the handle is retained for future use. And you should always clean up after yourself, even if AutoIt does so automatically - you will run into problems with other, less-forgiving languages if you do not get into the house-keeping habit.

M23


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

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

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

  • Similar Content

    • Nareshm
      By Nareshm
      If Process exits then end process and ;Some code here {1}
       
      If Process does not exits then ; My {1} Code
    • ur
      By ur
      How to retrieve the target executable path from a process.
      My system is effected with IMG001.exe virus and I remove the folders created by it daily but still it is creating the folders everytime I login to my PC.
      My Antivirus is not detecting it.

       
      So I thought to create a process in AutoIT to check for the process name IMG001.exe and retrieve the process target exe to a log file, so that I can track where it is putting these files.
      With  ProcessExists ( "process" ) , i can get the process ID.
      But how to get the target location of the executable of the process.??
    • salah kai
      By salah kai
      Hey everyone
      i wanna close a process by  path like
      C:\Users\salah\AppData\Local\Temp\a.exe
      processclose(C:\Users\salah\AppData\Local\Temp\a.exe)
      i tried to split the path but i don't know how to know last loop
      and thanks 
       
    • iXX
      By iXX
      Hi!
      Looking for working code to  get full path of process  - both 32 & 64 bit.
      I tryed this bellow, but it works only for 32-bit processes, even if compiled for x64...
      Thanx for suggestions!
       
      Func _ProcessGetPath($vProcess) ;get the program path done by MrCreatoR Local $iPID = ProcessExists($vProcess) If NOT $iPID Then Return SetError(1, 0, -1) Local $aProc = DllCall('kernel32.dll', 'hwnd', 'OpenProcess', 'int', BitOR(0x0400, 0x0010), 'int', 0, 'int', $iPID) If NOT IsArray($aProc) OR NOT $aProc[0] Then Return SetError(2, 0, -1) Local $vStruct = DllStructCreate('int[1024]') Local $hPsapi_Dll = DllOpen('Psapi.dll') If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@SystemDir & '\Psapi.dll') If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@WindowsDir & '\Psapi.dll') If $hPsapi_Dll = -1 Then Return SetError(3, 0, '') DllCall($hPsapi_Dll, 'int', 'EnumProcessModules', _ 'hwnd', $aProc[0], _ 'ptr', DllStructGetPtr($vStruct), _ 'int', DllStructGetSize($vStruct), _ 'int_ptr', 0) Local $aRet = DllCall($hPsapi_Dll, 'int', 'GetModuleFileNameEx', _ 'hwnd', $aProc[0], _ 'int', DllStructGetData($vStruct, 1), _ 'str', '', _ 'int', 2048) DllClose($hPsapi_Dll) If NOT IsArray($aRet) OR StringLen($aRet[3]) = 0 Then Return SetError(4, 0, '') Return $aRet[3] EndFunc  
    • ur
      By ur
      I have created below code to run the python file.
      #RequireAdmin #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Icon=icon.ico #AutoIt3Wrapper_Outfile=RunTaskRun.Exe #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.14.0 Author: Uday Kiran Reddy(ur) Script Function: To log python data to a file. #ce ---------------------------------------------------------------------------- #include <MsgBoxConstants.au3> #include "C:\Automation\ISMBuild\Library.au3" #include "ProcessEx_AddedNewEntryForLogging.au3" #include "CheckChangeinCommit.au3" If not NoChangesRequired() Then SendMail("Changes are in commit of erwin-main Repo","Will intimate once binaries are copied to Installshield machine") $hProcessHandle = _Process_RunCommand($PROCESS_RUN, $PROCESS_COMMAND & "C:\Python27\python.exe C:\BuildServer\AutoBuildServer\TaskRun.py") ; Capture the Process Handle $iPID = @extended ; Note the PID $returncode = _Process_DebugLogRunCommand($hProcessHandle, $iPID) ; Display the results in real-time Logging("Completed with ReturnCode "&$returncode) Else SendMail("No Changes are not there in commit of erwin-main Repo","So no Binaries for today.If it is needed, please remove the text file from location: "& @TempDir&"\git_erwin_commit.txt") EndIf When I kill the autoit execution exe in the middle of execution, it is not terminating the python.exe launched from script.
      Can you suggest how to do this?