iOS 实时获取当前应用消耗的CPU和内存
来源:互联网 发布:mysql可以没有主键吗 编辑:程序博客网 时间:2024/05/29 16:53
https://www.cnblogs.com/mobilefeng/p/4977783.html
这一遍文章对获取app 消耗的CPU和内存问题的多种方案做了对比,没有实际去测试。
1 获取应用消耗的CPU
float cpu_usage(){ kern_return_t kr; task_info_data_t tinfo; mach_msg_type_number_t task_info_count; task_info_count = TASK_INFO_MAX; kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count); if (kr != KERN_SUCCESS) { return -1; } task_basic_info_t basic_info; thread_array_t thread_list; mach_msg_type_number_t thread_count; thread_info_data_t thinfo; mach_msg_type_number_t thread_info_count; thread_basic_info_t basic_info_th; uint32_t stat_thread = 0; // Mach threads basic_info = (task_basic_info_t)tinfo; // get threads in the task kr = task_threads(mach_task_self(), &thread_list, &thread_count); if (kr != KERN_SUCCESS) { return -1; } if (thread_count > 0) stat_thread += thread_count; long tot_sec = 0; long tot_usec = 0; float tot_cpu = 0; int j; for (j = 0; j < thread_count; j++) { thread_info_count = THREAD_INFO_MAX; kr = thread_info(thread_list[j], THREAD_BASIC_INFO, (thread_info_t)thinfo, &thread_info_count); if (kr != KERN_SUCCESS) { return -1; } basic_info_th = (thread_basic_info_t)thinfo; if (!(basic_info_th->flags & TH_FLAGS_IDLE)) { tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds; tot_usec = tot_usec + basic_info_th->user_time.microseconds + basic_info_th->system_time.microseconds; tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0; } } // for each thread kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t)); assert(kr == KERN_SUCCESS); return tot_cpu;}
对于该方法获取的CPU消耗情况与Xcode 实时监控的CPU消耗情况基本一致。
2. 获取应用消耗的内存
该方法计算出来的内存消耗情况,与Xcode 统计的消耗情况相差太大(参考性不太大)。
还是贴出来:
// 有的是除以1024,有的是除以1000。+ (float)memoryUsage{ vm_size_t memory = memory_usage(); return memory / 1000.0 /1000.0;}vm_size_t memory_usage(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); return (kerr == KERN_SUCCESS) ? info.resident_size : 0; // size in bytes}
然后写一个单例类,添加一个定时器,隔一段时间调用一下该方法获取当前的内存和CPU消耗情况,同时写入本地文件中,以便后期分析。
简单写了一下,实现如下:
#import "HLMonitor.h"#import <mach/mach.h>#import <sys/time.h>static HLMonitor *instance = nil;@interface HLMonitor ()@property (nonatomic, assign) NSTimeInterval timeInterval;@end@implementation HLMonitor+ (instancetype)sharedInstance{ return [[[self class] alloc] init];}- (instancetype)init{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [super init]; }); return instance;}+ (instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [super allocWithZone:zone]; }); return instance;}- (void)startMonitorWithTimeInterval:(NSTimeInterval)timeInterval{ if (timeInterval <= 0) { timeInterval = 1.0; } self.timeInterval = timeInterval; NSString *filePath = [HLMonitor cpu_memoryLogPath]; NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:filePath]; [fileHandler seekToEndOfFile]; NSString *startLog = @"******************************开始统计cpu 和内存************************\n"; [fileHandler writeData:[startLog dataUsingEncoding:NSUTF8StringEncoding]]; [self saveMonitorLog];}- (void)saveMonitorLog{ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ float cpuUsage = [HLMonitor cpuUsage]; float memoryUsage = [HLMonitor memoryUsage]; struct tm* timeNow = [HLMonitor getCurTime]; NSString *monitorLog = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d.%ld | cpu 使用率:%.2f ----内存使用:%f\n", timeNow->tm_year, timeNow->tm_mon, timeNow->tm_mday, timeNow->tm_hour, timeNow->tm_min, timeNow->tm_sec, timeNow->tm_gmtoff, cpuUsage, memoryUsage]; NSLog(@"%@",monitorLog); NSString *filePath = [HLMonitor cpu_memoryLogPath]; NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:filePath]; [fileHandler seekToEndOfFile]; [fileHandler writeData:[monitorLog dataUsingEncoding:NSUTF8StringEncoding]]; [self saveMonitorLog]; });}+ (NSString *)cpu_memoryLogPath{ struct tm* timeNow = [self getCurTime]; NSArray* path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *nFilePath = [path objectAtIndex:0]; nFilePath = [nFilePath stringByAppendingPathComponent:@"CPUMemoryUsage"]; if (![[NSFileManager defaultManager] fileExistsAtPath:nFilePath]) { [[NSFileManager defaultManager] createDirectoryAtPath:nFilePath withIntermediateDirectories:NO attributes:nil error:nil]; } NSString *fileName = [NSString stringWithFormat:@"%d_%d_%d_CPU_Memory_Usage.log",timeNow->tm_year,timeNow->tm_mon,timeNow->tm_mday]; nFilePath = [nFilePath stringByAppendingPathComponent:fileName]; if (![[NSFileManager defaultManager] fileExistsAtPath:nFilePath]) { BOOL result = [[NSFileManager defaultManager] createFileAtPath:nFilePath contents:nil attributes:nil]; NSLog(@"%d",result); } return nFilePath;}+ (struct tm*)getCurTime{ //时间格式 struct timeval ticks; gettimeofday(&ticks, nil); time_t now; struct tm* timeNow; time(&now); timeNow = localtime(&now); timeNow->tm_gmtoff = ticks.tv_usec/1000; //毫秒 timeNow->tm_year += 1900; //tm中的tm_year是从1900至今数 timeNow->tm_mon += 1; //tm_mon范围是0-11 return timeNow;}+ (float)cpuUsage{ float cpu = cpu_usage(); return cpu;}+ (float)memoryUsage{ vm_size_t memory = memory_usage(); return memory / 1000.0 /1000.0;}vm_size_t memory_usage(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); return (kerr == KERN_SUCCESS) ? info.resident_size : 0; // size in bytes}float cpu_usage(){ kern_return_t kr; task_info_data_t tinfo; mach_msg_type_number_t task_info_count; task_info_count = TASK_INFO_MAX; kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count); if (kr != KERN_SUCCESS) { return -1; } task_basic_info_t basic_info; thread_array_t thread_list; mach_msg_type_number_t thread_count; thread_info_data_t thinfo; mach_msg_type_number_t thread_info_count; thread_basic_info_t basic_info_th; uint32_t stat_thread = 0; // Mach threads basic_info = (task_basic_info_t)tinfo; // get threads in the task kr = task_threads(mach_task_self(), &thread_list, &thread_count); if (kr != KERN_SUCCESS) { return -1; } if (thread_count > 0) stat_thread += thread_count; long tot_sec = 0; long tot_usec = 0; float tot_cpu = 0; int j; for (j = 0; j < thread_count; j++) { thread_info_count = THREAD_INFO_MAX; kr = thread_info(thread_list[j], THREAD_BASIC_INFO, (thread_info_t)thinfo, &thread_info_count); if (kr != KERN_SUCCESS) { return -1; } basic_info_th = (thread_basic_info_t)thinfo; if (!(basic_info_th->flags & TH_FLAGS_IDLE)) { tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds; tot_usec = tot_usec + basic_info_th->user_time.microseconds + basic_info_th->system_time.microseconds; tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0; } } // for each thread kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t)); assert(kr == KERN_SUCCESS); return tot_cpu;}@end
阅读全文
0 0
- iOS 实时获取当前应用消耗的CPU和内存
- linux windows下怎么获取当前进程的cpu 和内存的消耗的信息
- 消耗CPU和内存的脚本
- 获取当前进程的CPU使用率和内存使用
- 查看android程序的CPU和内存消耗情况
- 查看android程序的CPU和内存消耗情况
- 查看android程序的CPU和内存消耗情况
- adb看android程序的cpu和内存消耗
- 查看android程序的CPU和内存消耗情况
- 查看android程序的CPU和内存消耗情况
- 查看android程序的CPU和内存消耗情况
- Python CPU,内存实时获取
- FPS(检测内存和CPU消耗)
- php 获取代码执行时间和消耗的内存
- 编写shell脚本查看linux当前各用户的cpu和memory消耗比例
- ORALE实时查询最消耗CPU资源的SQL语句
- 查看当前应用cpu和内存使用情况
- .NET获取当前程序所在电脑的CPU和内存使用率
- SSM框架中-使用KindEditor+Nginx服务器+FTP服务,实现多文件上传
- how to populate values in dropdownbykey in webdynpro
- jdbc连接数据库
- Debugging hibernation and suspend
- 明明白白你的Linux服务器——硬件篇
- iOS 实时获取当前应用消耗的CPU和内存
- mark mybatis 返回boolean
- 数据校检Hibernate Validator 5.4.2.Final--前言
- iOS 静态库制作(Xcode9.0)
- 学习记录——Serlvet接口doGet()、doPost()
- xgboost 调参经验
- activeMQ搭建和简单使用
- 嵌入式文件系统启动顺序init
- Linux 查看历史命令并执行