iOS - 如何测量线程唤醒?

标签 ios multithreading instruments

我有一个应用程序由于太多“线程唤醒”而崩溃。例如:

过去 220 秒内有 45004 次唤醒(每次 205 次唤醒)
秒平均值),超过 300 秒内每秒 150 次唤醒的限制

这很难调试,因为我知道没有直接的方法来测量线程唤醒。我找到的最接近的是一个名为 System Trace 的 Instruments 模板,它会显示阻塞线程事件的数量。据推测,这是密切相关的,因为阻塞的线程意味着该线程将休眠,然后在它变得未阻塞时唤醒。

奇怪的是,当应用程序正常运行并且不崩溃时,阻塞线程的数量在每秒 10,000 的范围内。我的假设是,在某些情况下,阻塞的 sleep 线程仅计入您的“唤醒”限制 - 例如。我希望一个由于互斥锁而被锁定的线程计数,而操作系统在正常操作中简单地转换到其他线程不会。

如果 Instruments 有一个 Thread Wakeups 模板,我会很惊讶。我能找到的唯一文档在这里 - https://developer.apple.com/library/content/technotes/tn2151/_index.html :

The exception subtype WAKEUPS indicates that threads in the process are being woken up too many times per second, which forces the CPU to wake up very often and consumes battery life.

Typically, this is caused by thread-to-thread communication (generally using peformSelector:onThread: or dispatch_async) that is unwittingly happening far more often than it should be. Because the sort of communication that triggers this exception is happening so frequently, there will usually be multiple background threads with very similar Backtraces - indicating where the communication is originating.

最佳答案

请看这里https://developer.apple.com/forums/thread/124180在您的应用程序中有一个获取唤醒计数的代码的描述,而不仅仅是在仪器中。可以帮助您:

#include <mach/task.h>
#include <mach/mach.h>
BOOL GetSystemWakeup(NSInteger *interrupt_wakeup, NSInteger *timer_wakeup) {
  struct task_power_info info = {0};
  mach_msg_type_number_t count = TASK_POWER_INFO_COUNT;
  kern_return_t ret = task_info(current_task(), TASK_POWER_INFO, (task_info_t)&info, &count);
  if (ret == KERN_SUCCESS) {
    if (interrupt_wakeup) {
      *interrupt_wakeup = info.task_interrupt_wakeups;
    }
    if (timer_wakeup) {
      *timer_wakeup = info.task_timer_wakeups_bin_1 + info.task_timer_wakeups_bin_2;
    }
    return true;
  }
  else {
    if (interrupt_wakeup) {
      *interrupt_wakeup = 0;
    }
    if (timer_wakeup) {
      *timer_wakeup = 0;
    }
    return false;
  }
}
此外,您还可以找到唤醒次数过多的一些原因。

关于iOS - 如何测量线程唤醒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45511944/

相关文章:

ios - CADisplayLink 的变化间隔

objective-c - 将 UIImage 存储为核心数据中的可转换属性

multithreading - 为什么这个 go 代码输出这样?

c++ - 在 C++ 中像这样自动化互斥安全吗?

使用 Selenium + istanbul 的 javascript 代码覆盖率

ios - iOS 应用 CPU 徘徊在 100% 左右是否正常?

ios - 为什么在滚动 uitableviewcontroller 时会调用layoutIfNeeded?

ios - 通知画外音用户他们已突出显示容器中的元素

ios - Swift 3、iOS 10 - 以编程方式声明的 UIStackView 不适合屏幕宽度

c# - 如何并行运行两个线程?