gpt4 book ai didi

iOS 和 Mac 线程的 CPU 使用率

转载 作者:行者123 更新时间:2023-12-01 15:56:38 29 4
gpt4 key购买 nike

有谁知道是否可以获得应用程序中特定线程、进程或某些代码的 CPU 使用情况?如果你看一下 AUGraph,它有一个返回平均 CPU 使用率的函数。他们是怎么做到的?

最佳答案

我不确定这是否也适用于 iOS,但对于 OS X,您可以通过访问 Mach/BSD 子系统来获取所需的信息。基本上,您可以获得给定进程的线程列表,然后对所有线程的使用情况求和以获得进程的 CPU 使用情况。如果只需要一个线程cpu使用情况,则不需要求和。

它并不像人们希望的那样简单明了,但它就是这样(此代码基于 Amit Singh“Mac OS X 内部结构”):

            pid_t pid = ...;   //-- this is the process id you need info for
task_t port;
task_for_pid(mach_task_self(), pid, &port);

task_info_data_t tinfo;
mach_msg_type_number_t task_info_count;

task_info_count = TASK_INFO_MAX;
kr = task_info(port, TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
if (kr != KERN_SUCCESS) {
continue; //-- skip this task
}

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(port, &thread_list, &thread_count);
if (kr != KERN_SUCCESS) {
<HANDLE ERROR>
continue;
}
if (thread_count > 0)
stat_thread += thread_count;

long tot_sec = 0;
long tot_usec = 0;
long 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) {
<HANDLE ERROR>
continue;
}
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->system_time.microseconds + basic_info_th->system_time.microseconds;
tot_cpu = tot_cpu + basic_info_th->cpu_usage;
}

} // for each thread

我不知道是否有更好的方法来做到这一点,可能是这样,但这个方法对我有用。

关于iOS 和 Mac 线程的 CPU 使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6788274/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com