我的iPad运行时内存在哪里?
我正在导致设备(iPad)显然用完内存,所以它正在抛弃我的应用程序。 我正在试图了解仪器正在告诉我,我正在使用大约80Mb,并且没有其他应用程序在设备上运行。
我发现这个代码片断要求在iOS下的马赫系统的内存统计信息:
#import <mach/mach.h> #import <mach/mach_host.h> static 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); }
当我使用这个函数来获得三个内存值时,我发现mem_total值正在下降,即使mem_used总没有改变太多。 这里有两个连续的输出行:
<Warning>: used: 78585856 free: 157941760 total: 236527616
一些代码执行….
<Warning>: used 83976192 free: 10551296 total: 94527488
所以,我从一个157MB的空闲内存到10MB的空闲内存,但是我的使用率只能从78MB增加到84MB。 总内存从236MB减less到94MB。
这对任何人都有意义吗? 在这段时间内没有其他应用程序正在运行,该设备应该基本上完全致力于我的应用程序。
在两次内存检查之间执行的所有代码都是原生C ++代码,与任何Apple框架都没有交互。 确实有许多对内存系统的调用来从C ++堆中分配和释放对象,但正如所看到的,最终只分配了大约4MB的额外内存,剩下的所有内存都被释放/删除。
这可能是因为缺less的内存被堆碎片消耗掉吗? 即堆是简单的如此分散,块开销消耗所有额外的,不计算的内存?
有没有其他人看到这种行为?
谢谢,
-Eric
您应该使用task_info
而不是host_statistics
来检索应用程序的内存使用情况:
# include <mach/mach.h> # include <mach/mach_host.h> void dump_memory_usage() { 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( @"task_info: 0x%08lx 0x%08lx\n", info.virtual_size, info.resident_size ); } else { NSLog( @"task_info failed with error %ld ( 0x%08lx ), '%s'\n", kerr, kerr, mach_error_string( kerr ) ); } }