3

Possible Duplicate:
How to Programmatically Tell How Much Memory an iOS App is Using?

I need to know how much memory is used by an iPhone an application when the application is running in foreground or background. it will better if it shows memory useage in every 5 sec. is it possible to write a code to show the memory in use ? Any suggestion will be appriciated

Community
  • 1
  • 1
Saiful
  • 1,891
  • 1
  • 15
  • 39
  • Why don't you want to use Instruments to test this, it's a lot more powerful and flexible and avoids putting test code into your live project. – ikuramedia Aug 27 '12 at 19:45

2 Answers2

4

First include the method report_memory in the .h file then import

#import <mach/mach.h>

this to the .m file

After that write this line where you want to print the memory usage value

[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(report_memory) userInfo:nil repeats:YES];

then add this

-(void) report_memory {
    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(@"Memory usage: %.4lf MB", info.resident_size/1024.0/1024.0);
    } else {
        NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
    }
}

method to .m file

Jerome
  • 1,749
  • 1
  • 14
  • 40
Saiful
  • 1,891
  • 1
  • 15
  • 39
2

User NSTimer scheduled to run in 5 sec intervals. To get value of used memory, here you have some code

#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(@"Memory in use (in bytes): %u", info.resident_size);
    } else {
        NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
    }
}
pawelropa
  • 1,409
  • 1
  • 14
  • 20