Finding leaking memory - what function to use?

Mac OSX specific forum
User avatar
Shardik
Addict
Addict
Posts: 2058
Joined: Thu Apr 21, 2005 2:38 pm
Location: Germany

Re: Finding leaking memory - what function to use?

Post by Shardik »

jesperbrannmark wrote:Is there a function to return the amount of memory used by the program as a integer?
Try my procedure GetUsedMemory(). It's called from a window timer
every second and displays the program's memory usage in a small
window. The integer value in bytes returned from GetUsedMemory()
is converted to MB and displayed as a string with StrF and one digit
behind the decimal point. So you have the direct comparison to the
value displayed in the activity monitor.

You have to compile my code example to an app and start this app
together with the activity monitor. The running app should display
the same memory usage as the activity monitor... :wink:

I think the call of a mach kernel function is a much more appropriate
method to obtain the memory usage of a program than your lengthy
Applescript... :twisted:

Code: Select all

EnableExplicit

#TASK_BASIC_INFO_32 = 4

ImportC ""
  mach_task_self()
  task_info(TaskPort.I, InformationType.I, *TaskInfo, *BufferSize)
EndImport

Structure time_value
  Seconds.I
  Microseconds.I
EndStructure

Structure task_basic_info
  suspend_count.I
  virtual_size.I
  resident_size.I
  user_time.time_value
  system_time.time_value
  policy.I
EndStructure

Procedure.I GetUsedMemory()
  Protected TaskInfo.task_basic_info
  Protected TaskInfoSize.I
  Protected TaskPort.I

  TaskPort = mach_task_self()
  TaskInfoSize = SizeOf(task_basic_info)
  
  If task_info(TaskPort, #TASK_BASIC_INFO_32, @TaskInfo, @TaskInfoSize) = 0
    ProcedureReturn TaskInfo\resident_size
  EndIf

  ProcedureReturn
EndProcedure

Define i.I

OpenWindow(0, 270, 100, 170, 40, "Memory usage")
TextGadget(0, 10, 10, WindowWidth(0) - 20, 20, "", #PB_Text_Center)
SetGadgetText(0, StrF(GetUsedMemory() / 1048576, 1) + " MB")
AddWindowTimer(0, 0, 1000)

Repeat
  Select WaitWindowEvent()
    Case #PB_Event_CloseWindow
      Break
    Case #PB_Event_Timer
      SetGadgetText(0, StrF(GetUsedMemory() / 1048576, 1) + " MB")
  EndSelect
ForEver

RemoveWindowTimer(0, 0)