Jump to content


Photo

Using AHK to control/monitor Application RAM usage?


  • Please log in to reply
2 replies to this topic

#1 kareltehrobot

kareltehrobot
  • Members
  • 25 posts

Posted 22 May 2012 - 03:15 PM

I spent some time digging through the forums and looking at the general AHK function list and didn't find what I was looking for so I figured I'd ask here.

I want to use AHK to monitor RAM usage of a specific program and once it reaches a certain amount of memory to kill/restart it. Has anyone attempted something like this before?

#2 TheDewd

TheDewd
  • Members
  • 823 posts

Posted 22 May 2012 - 03:36 PM

<!-- l --><a class="postlink-local" href="http://www.autohotkey.com/community/viewtopic.php?p=223061#p223061">viewtopic.php?p=223061#p223061</a><!-- l -->

Using the function linked above, you would probably be able to do something like this... You would of course need to setup a timer to constantly check the process' memory usage.
[color=#BF0000]Proc := % GetProcessMemoryInfo( "firefox.exe" )

If (Proc > "400000") {  ; If RAM usage above 400000 K, then execute code...
   ;  Insert code here.
}[/color]

GetProcessMemoryInfo( pname )
{
   Process, Exist, %pname%
   pid := Errorlevel

   ; get process handle
   hProcess := DllCall( "OpenProcess", UInt, 0x10|0x400, Int, false, UInt, pid )

   ; get memory info
   VarSetCapacity( memCounters, 40, 0 )
   DllCall( "psapi.dll\GetProcessMemoryInfo", UInt, hProcess, UInt, &memCounters, UInt, 40 )
   DllCall( "CloseHandle", UInt, hProcess )

   list = cb,PageFaultCount,PeakWorkingSetSize,WorkingSetSize,QuotaPeakPagedPoolUsage
   ,QuotaPagedPoolUsage,QuotaPeakNonPagedPoolUsage,QuotaNonPagedPoolUsage
   ,PagefileUsage,PeakPagefileUsage

   n=0
   Loop, Parse, list, `,
   {
      n+=4
      SetFormat, Float, 0.0 ; round up K
      this := A_Loopfield
      this := NumGet( memCounters, (A_Index = 1 ? 0 : n-4), "UInt") / 1024

      ; omit cb
      If A_Index != 1
         info .= A_Loopfield . ": " . this . " K" . ( A_Loopfield != "" ? "`n" : "" )
   } 

   ; Return "[" . pid . "] " . pname . "`n`n" . info ; for everything
   Return WorkingSetSize := NumGet( memCounters, 12, "UInt" ) / 1024 ; what Task Manager shows
}
Note: I slightly modified the above code from the original source, removing the "K" from the result & deleting block of commented code.

#3 kareltehrobot

kareltehrobot
  • Members
  • 25 posts

Posted 22 May 2012 - 04:12 PM

Great, thanks a ton.