Page 1 of 1

detect memory leaks

Posted: Fri Oct 03, 2008 10:21 pm
by idle
I think I found this somewhere in the forum, though can't remember where but it's handy to help track down problematic memory leaks.

Code: Select all

Prototype.l GetProcessMemoryInfo_(hProcess.l, *p, cb.l)
 
 Procedure.l GetMemoryUsage(kilobytes.b=#True)
   Structure PROCESS_MEMORY_COUNTERS
      cb.l;DW
      PageFaultCount.l;DW
      PeakWorkingSetSize.l;SIZE_T
      WorkingSetSize.l;SIZE_T
      QuotaPeakPagedPoolUsage.l;SIZE_T
      QuotaPagedPoolUsage.l;SIZE_T
      QuotaPeakNonPagedPoolUsage.l;SIZE_T
      QuotaNonPagedPoolUsage.l;SIZE_T
      PagefileUsage.l;SIZE_T
      PeakPagefileUsage.l;SIZE_T
   EndStructure
   
   Static GetProcessMemoryInfo_.GetProcessMemoryInfo_
   Static PSAPI
   If Not GetProcessMemoryInfo_
      If Not PSAPI
         PSAPI=OpenLibrary(#PB_Any, "PSAPI.DLL")
      EndIf
      If PSAPI
         GetProcessMemoryInfo_=GetFunction(PSAPI, "GetProcessMemoryInfo")
      EndIf
   EndIf
   If GetProcessMemoryInfo_
      Protected p.PROCESS_MEMORY_COUNTERS
      GetProcessMemoryInfo_(GetCurrentProcess_(), @p, SizeOf(PROCESS_MEMORY_COUNTERS))
      
      If kilobytes
         ProcedureReturn (p\WorkingSetSize+p\PagefileUsage) /1024
      Else
         ProcedureReturn (p\WorkingSetSize + p\PagefileUsage) 
      EndIf
   EndIf
EndProcedure 

Posted: Sat Oct 04, 2008 10:33 am
by nicolaus
A small example will be nice to know how we must work with it :D

Posted: Sat Oct 04, 2008 12:49 pm
by Hroudtwolf
Hi,

Cool idea.

My slim version.

Code: Select all

Import "psapi.lib"
   GetProcessMemoryInfo( hProcess.l , *ppsmemCounters , dwCb.l ) 
EndImport

Structure PROCESS_MEMORY_COUNTERS
   lCb                        .l
   lPageFaultCount            .l
   lPeakWorkingSetSize        .l
   lWorkingSetSize            .l          
   lQuotaPeakPagedPoolUsage   .l
   lQuotaPagedPoolUsage       .l     
   lQuotaPeakNonPagedPoolUsage.l
   lQuotaNonPagedPoolUsage    .l
   lPagefileUsage             .l
   lPeakPagefileUsage         .l
EndStructure
    
Procedure.l GetProcessMemoryUsage ( blKiloBytes.l = #False )
   Protected PMC.PROCESS_MEMORY_COUNTERS

   If Not GetProcessMemoryInfo ( GetCurrentProcess_() , PMC , SizeOf( PROCESS_MEMORY_COUNTERS ) ) 
      ProcedureReturn -1
   EndIf
            
   If blKiloBytes
      ProcedureReturn ( PMC\lWorkingSetSize + PMC\lPagefileUsage ) / 1024 
   EndIf
   
   ProcedureReturn PMC\lWorkingSetSize + PMC\lPagefileUsage
EndProcedure

Debug Str ( GetProcessMemoryUsage ()        ) + " bytes."
Debug Str ( GetProcessMemoryUsage ( #True ) ) + " kilobytes."
Best regards

Wolf

Posted: Sat Oct 04, 2008 10:02 pm
by idle
@ Hroudtwolf

That certainly makes it clearer.