Question

As the title described, how can I programmatically get current memory usage (used or free...) in cocoa?

Please notice that what I needs is the memory usage for the system instead of current task only.

Thank you at advance!

Was it helpful?

Solution

You can get the task memory usage like this:

#import <mach/mach.h>

void report_memory(void) {
  struct task_basic_info info;
  mach_msg_type_number_t size = sizeof(info);
  kern_return_t kerr = task_info(mach_task_self(),
                                 TASK_BASIC_INFO,
                                 (task_info_t)&info,
                                 &size);
  if( kerr == KERN_SUCCESS ) {
    NSLog(@"Used memory (in bytes): %u", info.resident_size);
  } else {
    NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
  }
}

And the System memory usage like this:

#import <sys/sysctl.h>
#import <mach/host_info.h>
#import <mach/mach_host.h>
#import <mach/task_info.h>
#import <mach/task.h>
int mib[6]; 
mib[0] = CTL_HW;
mib[1] = HW_PAGESIZE;

int pagesize;
size_t length;
length = sizeof (pagesize);
if (sysctl (mib, 2, &pagesize, &length, NULL, 0) < 0)
{
    fprintf (stderr, "getting page size");
}

mach_msg_type_number_t count = HOST_VM_INFO_COUNT;

vm_statistics_data_t vmstat;
if (host_statistics (mach_host_self (), HOST_VM_INFO, (host_info_t) &vmstat, &count) != KERN_SUCCESS)
{
    fprintf (stderr, "Failed to get VM statistics.");
}

double total = vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count;
double wired = vmstat.wire_count / total;
double active = vmstat.active_count / total;
double inactive = vmstat.inactive_count / total;
double free = vmstat.free_count / total;

task_basic_info_64_data_t info;
unsigned size = sizeof (info);
task_info (mach_task_self (), TASK_BASIC_INFO_64, (task_info_t) &info, &size);

double unit = 1024 * 1024;
NSString *results = [NSString stringWithFormat: @"% 3.1f MB\n% 3.1f MB\n% 3.1f MB", vmstat.free_count * pagesize / unit, (vmstat.free_count + vmstat.inactive_count) * pagesize / unit, info.resident_size / unit];
NSLog (@"%@", results);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top