Objective-C/iOS 获取内存使用

获取内存总大小:

size_t size = sizeof(int);
int results;
int mib[2] = {CTL_HW, HW_PHYSMEM};
sysctl(mib, 2, &results, &size, NULL, 0);
return (NSUInteger) results;

需要引入头文件:

#include <sys/sysctl.h>

获取可用内存:

mach_port_t           host_port = mach_host_self();
mach_msg_type_number_t   host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
vm_size_t               pagesize;
vm_statistics_data_t     vm_stat;

host_page_size(host_port, &pagesize);

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

unsigned long mem_free = vm_stat.free_count * pagesize;

return mem_free;

需要引入头文件:

#import <mach/mach.h>

获取当前App使用内存:

struct task_basic_info info;
mach_msg_type_number_t size = TASK_BASIC_INFO_COUNT;//sizeof(info);
kern_return_t kerr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size);
return (kerr == KERN_SUCCESS) ? info.resident_size : 0; // size in bytes

同样需要引入头文件:

#import <mach/mach.h>

此方法可设置持续记录,可达到查看App使用是内存增减的情况。

    原文作者:WonderChang
    原文地址: https://www.jianshu.com/p/3dec1a222f46
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞