c++macosmemory

Get memory usage of a process from C++


I am trying to determine how much memory the current process is using, on Mac OS X. To be specific, how does top calculate the value displayed in the MEM column for each process? Activity Monitor displays the same value in the Memory column for each process on the Memory tab.

There are a few pages on the web (like this answer) suggesting the following:

struct task_basic_info tinfo;
mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
task_info(
    mach_task_self(), TASK_BASIC_INFO,
    (task_info_t) &tinfo, &count);
// memory usage is in tinfo.resident_size;

But the returned value is off by almost a factor 2 (eg top shows 64 MB, while this code reports 105MB). How do top and Activity Monitor find the memory usage of a process?


Solution

  • You want TASK_VM_INFO and the "phys_footprint" member. On all Apple OSes, you are only charged for "dirty" (written to) and "wired" memory. There are interesting edge cases with mapped files, but I won't get into those.

    That is now what top and Xcode use.