1

I would like to use this function to help monitor memory:

void print_free_memory ()
{
mach_port_t host_port;
mach_msg_type_number_t host_size;
vm_size_t pagesize;

host_port = mach_host_self();
host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
host_page_size(host_port, &pagesize);

vm_statistics_data_t vm_stat;

if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS)
    NSLog(@"Failed to fetch vm statistics");

/* Stats in bytes */
natural_t mem_used = (vm_stat.active_count +
                      vm_stat.inactive_count +
                      vm_stat.wire_count) * pagesize;
natural_t mem_free = vm_stat.free_count * pagesize;
natural_t mem_total = mem_used + mem_free;
NSLog(@"used: %u free: %u total: %u", mem_used, mem_free, mem_total);
}

A. Where do I put this function in my Xcode project?

B. How do I call it? Obviously I'd like to set up to continuously monitor memory.

soleil
  • 12,133
  • 33
  • 112
  • 183

2 Answers2

10

A. Where do I put this function in my Xcode project?

Put the definition in a separate .c file, and a declaration in a separate header file.

PrintFreeMem.h

extern void print_free_memory();

PrintFreeMem.c

#include "PrintFreeMem.h"
void print_free_memory() {
    // Your implementation
}

B. How do I call it?

You can call it the way you call regular C functions, after including its header file:

#include "PrintFreeMem.h"

-(void)myMethod {
    ...
    print_free_memory();
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 2
    +1 Only thing I would add (in case there is trouble) is that the project needs to know to compile the implementation file. This happens by default when you use the Xcode "new file" interface; but just in case it gives you a linking error, you need to add the .c file to your app's target. – Chris Trahey Aug 17 '12 at 04:26
  • Thanks. Now... what do these numbers mean? used: 3655589888 free: 631083008 total: 4286672896? 3.65 billion what? – soleil Aug 17 '12 at 04:32
  • 1
    @soleil My guess would be that this is the number of bytes: it looks like your host has 4G of memory installed, and roughly 3.6G of that is currently used. – Sergey Kalinichenko Aug 17 '12 at 04:36
  • Yeah... thanks. It seems that this isn't very useful for app memory management after all. – soleil Aug 17 '12 at 04:43
0

You can do the declaration in the header file and write this function in the implementation file or you can simply put the function in the implementation file but then function can be called only from the lines below

print_free_memory ();

Hope this works

Neo
  • 2,807
  • 1
  • 16
  • 18