iOS-从应用程序获取CPU使用率

有谁知道如何获取应用程序的CPU使用率?绝对有可能,因为应用商店中有一些可以显示它的应用程序(Activity Monitor Touch)。


交互式爱情
浏览 1073回答 3
3回答

烙印99

尝试这个:- (NSString *)cpuUsage{&nbsp; &nbsp;kern_return_t kr;&nbsp; &nbsp;task_info_data_t tinfo;&nbsp; &nbsp;mach_msg_type_number_t task_info_count;&nbsp; &nbsp;task_info_count = TASK_INFO_MAX;&nbsp; &nbsp;kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);&nbsp; &nbsp;if (kr != KERN_SUCCESS)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp;return @"NA";&nbsp; &nbsp;}&nbsp; &nbsp;task_basic_info_t&nbsp; &nbsp; &nbsp; basic_info;&nbsp; &nbsp;thread_array_t&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;thread_list;&nbsp; &nbsp;mach_msg_type_number_t thread_count;&nbsp; &nbsp;thread_info_data_t&nbsp; &nbsp; &nbsp;thinfo;&nbsp; &nbsp;mach_msg_type_number_t thread_info_count;&nbsp; &nbsp;thread_basic_info_t basic_info_th;&nbsp; &nbsp;uint32_t stat_thread = 0; // Mach threads&nbsp; &nbsp;basic_info = (task_basic_info_t)tinfo;&nbsp; &nbsp;// get threads in the task&nbsp; &nbsp;kr = task_threads(mach_task_self(), &thread_list, &thread_count);&nbsp; &nbsp;if (kr != KERN_SUCCESS)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; return @"NA";&nbsp; &nbsp;}&nbsp; &nbsp;if (thread_count > 0)&nbsp; &nbsp; stat_thread += thread_count;&nbsp; &nbsp;long tot_idle = 0;&nbsp; &nbsp;long tot_user = 0;&nbsp; &nbsp;long tot_kernel = 0;&nbsp; &nbsp;int j;&nbsp; &nbsp;for (j = 0; j < thread_count; j++)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; thread_info_count = THREAD_INFO_MAX;&nbsp; &nbsp; &nbsp; kr = thread_info(thread_list[j], THREAD_BASIC_INFO,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(thread_info_t)thinfo, &thread_info_count);&nbsp; &nbsp; &nbsp; if (kr != KERN_SUCCESS)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return nil;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; basic_info_th = (thread_basic_info_t)thinfo;&nbsp; &nbsp; &nbsp; if (basic_info_th->flags & TH_FLAGS_IDLE)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //This is idle&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tot_idle = tot_idle + basic_info_th->user_time.microseconds + basic_info_th->system_time.microseconds;&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //This is user&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tot_user = tot_user + basic_info_th->user_time.microseconds;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //This is kernel&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tot_kernel = tot_kernel + basic_info_th->system_time.microseconds;&nbsp; &nbsp; &nbsp; }&nbsp; } // for each thread&nbsp; kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));&nbsp; assert(kr == KERN_SUCCESS);&nbsp; long tot_cpu = tot_idle + tot_user + tot_kernel&nbsp; return [NSString stringWithFormat:@"Idle: %.2f, User: %.2f, Kernel: %.2f", tot_idle/tot_cpu, tot_user/tot_cpu, tot_kernel/tot_cpu];}但是,该方法会根据每个过程的起点来计算百分比。如果您正在寻找更传统的方法来计算这些数字
打开App,查看更多内容
随时随地看视频慕课网APP