晚晚皆安 發表於 2024-7-17 17:03:00

iOS开发基础124-RunLoop实现卡顿检测

<p>利用 <code>RunLoop</code> 实现卡顿检测的基本思路是通过监听 <code>RunLoop</code> 的状态变化来判断主线程的执行时长。如果 <code>RunLoop</code> 在某个状态停留的时间超过了预设的时间阈值,则认为发生了卡顿。在具体实现中,可以利用 <code>CFRunLoopObserver</code> 来监听 <code>RunLoop</code> 的状态变化,并记录时间差。</p>
<h3 id="一卡顿检测的基本原理">一、卡顿检测的基本原理</h3>
<p>在 iOS 应用中,<code>RunLoop</code> 对主线程事件的处理可以细分为多个状态,包括 <code>beforeSources</code>、<code>afterWaiting</code> 等。通过添加 <code>CFRunLoopObserver</code>,我们可以在 <code>RunLoop</code> 进入和退出这些状态时执行自定义代码:</p>
<ul>
<li><strong>beforeSources</strong>:即将在处理 Source 事件前触发。</li>
<li><strong>afterWaiting</strong>:从休眠状态唤醒后触发。</li>
</ul>
<p>通过在这两个状态之间记录时间差,如果该时间差超过预设的阈值(如 200ms),则认为发生了卡顿。</p>
<h3 id="二实现步骤">二、实现步骤</h3>
<ol>
<li><strong>创建并配置 CFRunLoopObserver</strong></li>
<li><strong>监听适当的 RunLoop 状态</strong></li>
<li><strong>记录时间并判断卡顿</strong></li>
<li><strong>记录卡顿信息</strong></li>
</ol>
<h3 id="三卡顿检测封装示例">三、卡顿检测封装示例</h3>
<p>以下是一个利用 <code>RunLoop</code> 实现卡顿检测的完整示例,并进行了封装:</p>
<pre><code class="language-objective-c">#import &lt;Foundation/Foundation.h&gt;
#import &lt;CoreFoundation/CoreFoundation.h&gt;

@interface LagMonitor : NSObject {
    CFRunLoopObserverRef _observer;
    CFRunLoopActivity _activity;
    dispatch_semaphore_t _semaphore;
    NSTimeInterval _threshold; // 时间阈值 (单位: 秒)
}

@property (nonatomic, assign) BOOL isMonitoring;

+ (instancetype)sharedInstance;
- (void)startMonitoring;
- (void)stopMonitoring;

@end

@implementation LagMonitor

+ (instancetype)sharedInstance {
    static LagMonitor *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&amp;onceToken, ^{
      instance = [ init];
    });
    return instance;
}

- (instancetype)init {
    self = ;
    if (self) {
      _semaphore = dispatch_semaphore_create(0);
      _threshold = 0.2; // 默认阈值 200ms
      _activity = 0;
    }
    return self;
}

- (void)startMonitoring {
    if (self.isMonitoring) return;
    self.isMonitoring = YES;

    CFRunLoopObserverContext context = {0, (__bridge void *)self, NULL, NULL, NULL};

    _observer = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                        kCFRunLoopAllActivities,
                                        YES,
                                        0,
                                        &amp;runLoopObserverCallBack,
                                        &amp;context);

    if (_observer) {
      CFRunLoopRef runLoop = CFRunLoopGetMain();
      CFRunLoopAddObserver(runLoop, _observer, kCFRunLoopCommonModes);

      // 开启一个子线程用于时间监控
      __weak typeof(self) weakSelf = self;
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            while (strongSelf &amp;&amp; strongSelf.isMonitoring) {
                long result = dispatch_semaphore_wait(strongSelf-&gt;_semaphore, dispatch_time(DISPATCH_TIME_NOW, strongSelf-&gt;_threshold * NSEC_PER_SEC));
                if (result != 0) {
                  if (!strongSelf-&gt;_observer) {
                        strongSelf-&gt;_semaphore = 0;
                        strongSelf-&gt;_activity = 0;
                        return;
                  }
                  if (strongSelf-&gt;_activity == kCFRunLoopBeforeSources || strongSelf-&gt;_activity == kCFRunLoopAfterWaiting) {
                        // 检测到卡顿,记录或上报卡顿信息
                        ;
                  }
                }
            }
      });
    }
}

- (void)stopMonitoring {
    if (!self.isMonitoring) return;
    self.isMonitoring = NO;

    if (_observer) {
      CFRunLoopRemoveObserver(CFRunLoopGetMain(), _observer, kCFRunLoopCommonModes);
      CFRelease(_observer);
      _observer = NULL;
    }
    // 销毁信号量
    _semaphore = nil;
}

void runLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
    LagMonitor *monitor = (__bridge LagMonitor *)info;
    monitor-&gt;_activity = activity;
    dispatch_semaphore_signal(monitor-&gt;_semaphore);
}

- (void)logLag {
    // 打印或记录卡顿信息
    NSLog(@"Detect a lag!");
}

@end
</code></pre>
<h3 id="四使用示例">四、使用示例</h3>
<pre><code class="language-objective-c">#import "LagMonitor.h"

// 在应用启动或适当时机启用卡顿监控
[ startMonitoring];

// 停止监控
[ stopMonitoring];
</code></pre>
<h3 id="五关键点解析">五、关键点解析</h3>
<ol>
<li>
<p><strong>CFRunLoopObserver 使用</strong></p>
<ul>
<li><code>CFRunLoopObserverCreate</code> 用于创建 RunLoop 观察者,并配置所关心的状态变化。</li>
<li><code>CFRunLoopObserverContext</code> 提供了上下文信息,以便在回调中使用。</li>
</ul>
</li>
<li>
<p><strong>线程监控</strong></p>
<ul>
<li>通过 GCD 创建一个高优先级的子线程时刻等待 <code>RunLoop</code> 状态的变化。</li>
<li>使用 <code>dispatch_semaphore</code> 实现线程间同步,并通过信号量判断 <code>RunLoop</code> 是否在某状态间隔超时。</li>
</ul>
</li>
<li>
<p><strong>阈值设置</strong></p>
<ul>
<li><code>_threshold</code> 是用来设置卡顿的时间阈值,例如 0.2 秒可以检测超过 200 毫秒的卡顿。</li>
</ul>
</li>
<li>
<p><strong>封装接口</strong></p>
<ul>
<li>提供 <code>startMonitoring</code> 和 <code>stopMonitoring</code> 方法,可以方便地启动和停止监测卡顿。</li>
</ul>
</li>
</ol>
<h3 id="六总结">六、总结</h3>
<p>通过利用 <code>RunLoop</code> 的观察者功能,我们能够准确地捕捉到 <code>RunLoop</code> 的状态变化,并通过时间阈值来判断卡顿现象。这种方法可以帮助我们在开发和调试过程中及时发现和解决性能问题,提高应用的响应速度和用户体验。这种封装方式也使得卡顿检测的启用和停止变得简单易用,适合集成到各种 iOS 项目中。</p>


</div>
<div id="MySignature" role="contentinfo">
    将来的你会感谢今天如此努力的你!
版权声明:本文为博主原创文章,未经博主允许不得转载。<br><br>
来源:https://www.cnblogs.com/chglog/p/18307840
頁: [1]
查看完整版本: iOS开发基础124-RunLoop实现卡顿检测