objective-c - iPhone如何用编程检索内存使用?
ringa_lee
ringa_lee 2017-04-21 11:18:53
0
1
645

我想以编程的方式随时检索iPhone App的内存使用量。是的,我注意到了ObjectAlloc/Leaks。但我对那些不感兴趣,只想知道是否可以通过写代码来获取所使用的字节量,并通过NSLog报告。
谢谢!

原问题:Programmatically retrieve memory usage on iPhone

ringa_lee
ringa_lee

ringa_lee

reply all(1)
小葫芦

Jason Coco:
In order to get the memory bytes actually used by the App, you can use the following method. However, you must become proficient in various analysis tools, as they design a better-looking picture of overall usage.

#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));
  }
}

There is a field in info.virtual_size that tells you the exact number of bytes of virtual memory available (or in any case the potential virtual memory allocated to the app). The code linked by Pgb will give you the available memory and memory type of the device.


Douglas K. Bell:
This is an enhanced report_memory() that can quickly show memory leaks in NSLog().

void report_memory(void) {
    static unsigned last_resident_size=0;
    static unsigned greatest = 0;
    static unsigned last_greatest = 0;

    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 ) {
        int diff = (int)info.resident_size - (int)last_resident_size;
        unsigned latest = info.resident_size;
        if( latest > greatest   )   greatest = latest;  // track greatest mem usage
        int greatest_diff = greatest - last_greatest;
        int latest_greatest_diff = latest - greatest;
        NSLog(@"Mem: %10u (%10d) : %10d :   greatest: %10u (%d)", info.resident_size, diff,
          latest_greatest_diff,
          greatest, greatest_diff  );
    } else {
        NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
    }
    last_resident_size = info.resident_size;
    last_greatest = greatest;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template