内存检测

1、引入头文件

#include <sys/sysctl.h>

#include <mach/mach.h>

2、检测函数

//MARK: 可用内存
- (double)availableMemory
{
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(),HOST_VM_INFO,(host_info_t)&vmStats,&infoCount);
    if(kernReturn != KERN_SUCCESS) 
    {
        return NSNotFound;
    }
    return ((vm_page_size * vmStats.free_count) / 1024.0) / 1024.0;
}


//MARK: 已使用内存
- (double)usedMemory
{
    task_basic_info_data_t taskInfo;
    mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
    kern_return_t kernReturn = task_info(mach_task_self(),
                                         TASK_BASIC_INFO, (task_info_t)&taskInfo, &infoCount);
    if(kernReturn != KERN_SUCCESS) {
        return NSNotFound;
    }
    return taskInfo.resident_size / 1024.0 / 1024.0;
}

3、输出内存状况:

每隔三秒输出一次内存使用情况:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 
                                             target:self 
                                           selector:@selector(onTimer:) 
                                           userInfo:nil 
                                            repeats:YES];
 

- (void)onTimer:(id)sender
{
     NSLog(@" 使用内存  %f  剩余内存  %f",[self usedMemory],[self availableMemory]);
}
posted @ 2012-05-04 08:15  FoxBabe  阅读(647)  评论(3编辑  收藏  举报