iOS获取App占用内存,占用CPU

2021-10-20  本文已影响0人  iOS_zy

首先导入

#import <sys/sysctl.h>
#import <mach/mach.h>
///内存
- (int64_t)memoryUsage {
    int64_t memoryUsageInByte = 0;
        task_vm_info_data_t vmInfo;
        mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
        kern_return_t kernelReturn = task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &vmInfo, &count);
        if(kernelReturn == KERN_SUCCESS) {
            memoryUsageInByte = (int64_t) vmInfo.phys_footprint;
            NSLog(@"Memory in use (in bytes): %lld", memoryUsageInByte);
        } else {
            NSLog(@"Error with task_info(): %s", mach_error_string(kernelReturn));
        }
        return memoryUsageInByte;
}
//CPU占用
- (double)getCpuUsage {
    kern_return_t           kr;
    thread_array_t          threadList;         // 保存当前Mach task的线程列表
    mach_msg_type_number_t  threadCount;        // 保存当前Mach task的线程个数
    thread_info_data_t      threadInfo;         // 保存单个线程的信息列表
    mach_msg_type_number_t  threadInfoCount;    // 保存当前线程的信息列表大小
    thread_basic_info_t     threadBasicInfo;    // 线程的基本信息
    
    // 通过“task_threads”API调用获取指定 task 的线程列表
    //  mach_task_self_,表示获取当前的 Mach task
    kr = task_threads(mach_task_self(), &threadList, &threadCount);
    if (kr != KERN_SUCCESS) {
        return -1;
    }
    double cpuUsage = 0;
    for (int i = 0; i < threadCount; i++) {
        threadInfoCount = THREAD_INFO_MAX;
        // 通过“thread_info”API调用来查询指定线程的信息
        //  flavor参数传的是THREAD_BASIC_INFO,使用这个类型会返回线程的基本信息,
        //  定义在 thread_basic_info_t 结构体,包含了用户和系统的运行时间、运行状态和调度优先级等
        kr = thread_info(threadList[i], THREAD_BASIC_INFO, (thread_info_t)threadInfo, &threadInfoCount);
        if (kr != KERN_SUCCESS) {
            return -1;
        }
        
        threadBasicInfo = (thread_basic_info_t)threadInfo;
        if (!(threadBasicInfo->flags & TH_FLAGS_IDLE)) {
            cpuUsage += threadBasicInfo->cpu_usage;
        }
    }
    
    // 回收内存,防止内存泄漏
    vm_deallocate(mach_task_self(), (vm_offset_t)threadList, threadCount * sizeof(thread_t));

    return cpuUsage / (double)TH_USAGE_SCALE * 100.0;
}

- (void)logConfig{
    NSLog(@"系统是:%@", [[UIDevice currentDevice] systemVersion]);
    NSLog(@"开始检测内存占用");
    NSLog(@"CPU占用是:%.1f%%", [self getCpuUsage]);
    NSLog(@"占用内存是:%.1fM", [self memoryUsage] / 1024.0 / 1024.0);
    NSLog(@"结束");
}

以上是实现方式,和调用。
想看原理:https://www.jianshu.com/p/95df83780c8f

上一篇下一篇

猜你喜欢

热点阅读