Jump to content

_ReduceMemory UDF


jftuga
 Share

Recommended Posts

it is better to use GetCurrentProcess for the own Process and not OpenProcess :)

Func _ReduceMemory($ProcID = 0)
; Original version : w_Outer
; modified by Rajesh V R to include process ID
; modified by Prog@ndy to include process handle
    
    If $ProcID = 0 or ProcessExists($ProcID) = 0 Then ; No process id specified or process doesnt exist - use current process instead.
        Local $ai_GetCurrentProcess = DllCall('kernel32.dll', 'ptr', 'GetCurrentProcess')
        Local $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'ptr', $ai_GetCurrentProcess[0])
        Return $ai_Return[0]
    EndIf
   
    Local $ai_Handle = DllCall("kernel32.dll", 'ptr', 'OpenProcess', 'int', 0x1f0fff, 'int', False, 'int', $ProcID)
    Local $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'ptr', $ai_Handle[0])
    DllCall('kernel32.dll', 'int', 'CloseHandle', 'ptr', $ai_Handle[0])
    Return $ai_Return[0]

EndFunc
Good work.

Based on the link thet SmOke_N supplied, starting with Windows 7 psapi.dll is not used at all. It just uses kernel32.dll for everything so you may want to look into mods based on that.

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

  • 3 weeks later...

Based on the link thet SmOke_N supplied, starting with Windows 7 psapi.dll is not used at all. It just uses kernel32.dll for everything so you may want to look into mods based on that.

So I assume this should work for WIN7? Have no system at hand to test :D . Oh, and rereading the article, has anyone an "Windows Server 2008 R2" at hand to check the Fileversion of "WinVer.exe"?

Edit:

Removed code because it crashed on WIN7 :D

Edited by KaFu
Link to comment
Share on other sites

  • Moderators

I'm quite sure the psapi.dll calls are backwards compatible. Win7 does have psapi.dll, it's just stated that the functions are in kernel32 dll now. I guess it's safer to do it this way, but I seriously doubt they'll break all the 32bit apps out there by removing the dll and or it's compatibility.

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

  • 4 months later...

Some error checking added by Prog@ndy for this thread:

http://www.autoitscript.com/forum/index.php?showtopic=103693

Func _ReduceMemory($ProcID = 0)
    ; Original version : w_Outer
    ; modified by Rajesh V R to include process ID
    ; modified by Prog@ndy
    Local $ai_Return, $ai_Handle
    If $ProcID <= 0 Then ; No process id specified - use current process instead.
        $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'ptr', -1)
        If @error Then Return SetError(1, 0, 0)
        Return $ai_Return[0]
    EndIf

    $ProcID = ProcessExists($ProcID)
    If $ProcID = 0 Then Return SetError(2, 0, 0)
    $ai_Handle = DllCall("kernel32.dll", 'ptr', 'OpenProcess', 'dword', 0x1f0fff, 'int', False, 'dword', $ProcID)
    If @error Or $ai_Handle[0] = 0 Then Return SetError(3, 0, 0)
    $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'ptr', $ai_Handle[0])
    If @error Then
        DllCall('kernel32.dll', 'int', 'CloseHandle', 'ptr', $ai_Handle[0])
        Return SetError(4, 0, 0)
    EndIf
    DllCall('kernel32.dll', 'int', 'CloseHandle', 'ptr', $ai_Handle[0])
    Return $ai_Return[0]

EndFunc   ;==>_ReduceMemory
Thanks Prog@ndy

[size="1"][font="Arial"].[u].[/u][/font][/size]

Link to comment
Share on other sites

  • 2 weeks later...

forgot to close the handle:

Func _ReduceMemory()
    Local $ai_GetCurrentProcessId = DllCall('kernel32.dll', 'int', 'GetCurrentProcessId')
    Local $ai_Handle = DllCall("kernel32.dll", 'int', 'OpenProcess', 'int', 0x1f0fff, 'int', False, 'int', $ai_GetCurrentProcessId[0])
    Local $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'long', $ai_Handle[0])
    DllCall('kernel32.dll', 'int', 'CloseHandle', 'int', $ai_Handle[0])
    Return $ai_Return[0]
EndFunc

I'm a little confused. In the dllcall "OpenProcess" you have: 'int', 0x1f0fff

However, when i look at MSDN, it says that it should be a DWORD value. Also, 0x1f0fff is not listed as a process access flag HERE

So, what's with that? I'm just trying to understand.

Link to comment
Share on other sites

Don't worry about things you don't understand. For all intents, int and dword are equivalent here. That value specifies PROCESS_ALL_ACCESS, which is unecessary overkill anyway. You only need PROCESS_QUERY_INFORMATION and PROCESS_SET_INFORMATION and PROCESS_SET_QUOTA. Change the parameter to 'dword' and 0x0700.

Edited by wraithdu
Link to comment
Share on other sites

quite interesting, few things got way beyond my depth in dll / process handling knowledge, thats why i had to remain silent :-)

one thing to comment is about win 7 - as mentioned, they have put them in kernel dll file and not have removed it yet but there is all chances it gets ignored anymore or in case of errors it may not be supported. probably we will wake this thread again when we face errors beyong win7 and also, we need to get it tested in all 6 editions of win7 (there should be no errors assuming current case) if some gets hold of them ...

Link to comment
Share on other sites

  • 1 year later...

I ran into a situation where I needed to make sure the Dlls were opened and closed in the function,

Func _ReduceMemory($ProcID = 0)
    ; Original version : w_Outer
    ; modified by Rajesh V R to include process ID
    ; modified by Prog@ndy
    ; Modified by Merrik
    Local $ai_Return, $ai_Handle
    Local $DllK = DllOpen("kernel32.dll")
    Local $DllP = DllOpen("psapi.dll")

    If $ProcID <= 0 Then ; No process id specified - use current process instead.
        $ai_Return = DllCall($DllP, 'int', 'EmptyWorkingSet', 'ptr', -1)
        If @error Then Return SetError(1, 0, 0)
        Return $ai_Return[0]
    EndIf

    $ProcID = ProcessExists($ProcID)
    If $ProcID = 0 Then Return SetError(2, 0, 0)
    $ai_Handle = DllCall($DllK, 'ptr', 'OpenProcess', 'dword', 0x1f0fff, 'int', False, 'dword', $ProcID)
    If @error Or $ai_Handle[0] = 0 Then Return SetError(3, 0, 0)
    $ai_Return = DllCall($DllP, 'int', 'EmptyWorkingSet', 'ptr', $ai_Handle[0])
    If @error Then
        DllCall($DllK, 'int', 'CloseHandle', 'ptr', $ai_Handle[0])
        Return SetError(4, 0, 0)
    EndIf
    DllCall($DllK, 'int', 'CloseHandle', 'ptr', $ai_Handle[0])
    Return $ai_Return[0]
    DllClose($DllK)
    DllClose($DllP)


EndFunc   ;==>_ReduceMemory so I thought I would add this part in.
Edited by Merrik
Link to comment
Share on other sites

I don't this is a problem or required about closing the DLL, why not use _WinAPI_EmptyWorkingSet() in WinAPIEx.au3 by Yashied.

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

An Example is in the Help File provided by Yashied. All you do is call the Function by using _WinAPI_EmptyWorkingSet() if you want to use the running EXE.

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Cool! This was the first time I've seen this. Looks good. I will test. Do you know it works on Windows 7?

Yeh it does, x32 & x64.

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • 4 months later...

All this does is force Windows to page out working memory to the pagefile. It doesn't "free" any memory, and may in fact have performance hits for a running application, because it forces a hard drive access twice (once when you call it, once again when that page is needed again.)

Windows will automatically do this for you if your free memory drops to critical. That's one reason why your machine is so much slower in those situations, because of all those page faults.

The only situation this would be useful is in a long-running, little-executing process, such as a background service, that spends most of it's time sleeping. In those cases, this call acts as something of a "OK I'm idle, you can put my memory away to the hard drive until I want it again." Using this in a foreground application as a means to artificially keep the physical memory size down is just :graduated:

.

Link to comment
Share on other sites

Typically, after calling this function, memory usage does not exceed 30-40% of the size that initialized by AutoIt. For example:

#Include <WinAPIEx.au3>

_WinAPI_EmptyWorkingSet()

While 1
    Sleep(1000)
WEnd

664 KB vs. 10.184 MB (without _WinAPI_EmptyWorkingSet())

Anyway, this function should be used wisely.

Edited by Yashied
Link to comment
Share on other sites

The point was that it doesn't actually lower memory usage, just change the location at which those memory pages are stored. Windows will automatically page out as necessary if your physical memory approaches critical. Why cut your performance at all, for 10MB that you don't need anyway? If you did, it would already be paged out.

.

Link to comment
Share on other sites

@Unsign: Force thrashing? It makes my HD purr like a kitten. :graduated:

@Yashied '0x001F0FFF' VS '0x00000700' as wraithdu said.

Also

DllCall('kernel32.dll', 'ptr', 'OpenProcess',...

vs.

_WinAPI_OpenProcess(...

Just late night copypasta or reasoning behind this?

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...