iOS app性能监控

690 阅读1分钟

App 作为进程运行起来后会有多个线程,每个线程对 CPU 的使用率不同。各个线程对 CPU 使用率的总和,就是当前 App 对 CPU 的使用率。明白了这一点以后,我们也就摸清楚了对 CPU 使用率进行线上监控的思路。

在 iOS 系统中,你可以在 /usr/include/mach/thread_info.h (macOS Catalina系统 为/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/mach/thread_info.h) 里看到线程基本信息的结构体,其中的 cpu_usage 就是 CPU 使用率。结构体的完整代码如下所示:

struct thread_basic_info {
  time_value_t    user_time;     // 用户运行时长
  time_value_t    system_time;   // 系统运行时长
  integer_t       cpu_usage;     // CPU 使用率
  policy_t        policy;        // 调度策略
  integer_t       run_state;     // 运行状态
  integer_t       flags;         // 各种标记
  integer_t       suspend_count; // 暂停线程的计数
  integer_t       sleep_time;    // 休眠的时间
};