我想以编程的方式随时检索iPhone App的内存使用量。是的,我注意到了ObjectAlloc/Leaks。但我对那些不感兴趣,只想知道是否可以通过写代码来获取所使用的字节量,并通过NSLog报告。
谢谢!
原问题:Programmatically retrieve memory usage on iPhone
高洛峰2017-04-21 11:20:53
Jason Coco:
为了获得App实际使用的内存字节,你可以使用下述方式。但是,你必须要熟练掌握各种分析工具,就像它们设计了更好看的表示整体使用的图片一样。
#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));
}
}
info.virtual_size中有个字段可以告诉你可用的虚拟内存的具体字节数(或者任何情况下内存分配给App的潜在虚拟内存)。Pgb链接的代码将为你提供设备的可用内存和内存类型。
Douglas K. Bell:
这是加强后的report_memory(),可以在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;
}