3

I am using the following to get the memory usage:

 struct task_basic_info info;
    mach_msg_type_number_t sizeNew = sizeof(info);
    kern_return_t kerr = task_info(mach_task_self(),
                                   TASK_BASIC_INFO,
                                   (task_info_t)&info,
                                   &sizeNew);
    if( kerr == KERN_SUCCESS ) {
        printf("Memory in use (in bytes): %u", info.resident_size);
    } else {
        printf("Error with task_info(): %s", mach_error_string(kerr));

    }

But the memory returned by this is much higher than that of shown by XCode6, any one else facing the same issue ?

1 Answers1

1

Resident set size (RSIZE) is not the same as the 'amount of memory used'. it includes the code as well.

You're probably looking for the top equivalent of RPRVT from the top program.

Obtaining that information requires walking the VM information for the process. Using the code for libtop.c, function libtop_update_vm_regions as a template, you would need to walk through the entire memory map adding up all the private pages. There's a simpler example of walking the address space, which can be used as a basis for calculating this size. You're looking for the VPRVT value, not the RPRVT value.

I don't currently have a mac to hand to write out an example with any degree of confidence that would work.

Community
  • 1
  • 1
Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
  • Hi , Yes I tried your approach too, but there is also a problem .- task_t task = mach_task_self(); while (true) { mach_msg_type_number_t count = VM_REGION_TOP_INFO_COUNT; myaddr += mysize; ret = vm_region_64(mytask, &myaddr, &mysize, VM_REGION_TOP_INFO, (vm_region_info_64_t)&myinfo, &mycount, &myobject_name); if (ret != KERN_SUCCESS) break; my_private_pages += myinfo.private_pages_resident; } int pageSize = getpagesize(); – Abhisek Mishra Mar 04 '15 at 10:06
  • Now if you see vmmemory size it contain pages of size 4K even for 64 bit, where as getMemorySize returns size of 16K . – Abhisek Mishra Mar 04 '15 at 10:07
  • Standard pages are 4k for all 32&64bit OSX systems based on the x86 architecture. There are large pages (2mb), but those tend to be allocated in exceptional circumstances. I have no idea about `getMemorySize` or what it does - based on some googling it's a third party function call. `getpagesize()` should be considered the 'right' value. (as mentioned in my answer, my mac is currently in for repairs so this is all based off memory & google; I can't check things directly myself) – Anya Shenanigans Mar 04 '15 at 10:38