用代码监控FPS值(CADisplayLink)

2019-08-19  本文已影响0人  寂寞先森666

主要用的是CADisplayLink:一个和屏幕刷新率相同定时器。

创建CADisplayLink对象的时候会指定一个selector,把创建的CADisplayLink对象加入runloop,所以就实现了以屏幕刷新的频率调用某个方法。

在调用的方法中计算执行的次数,用次数除以时间,就算出了FPS。

注:iOS正常刷新率为每秒60次

@interface ViewController ()
@property(strong,nonatomic)CADisplayLink * playLink;
@property(assign,nonatomic)int performTimes;
@property(assign,nonatomic)int lastTimestamp;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化CADisplayLink
    self.playLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkAction:)];
    // 把CADisplayLink对象加入runloop
    [self.playLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    self.performTimes = 0;
    self.lastTimestamp = 0;
}
-(void)displayLinkAction:(CADisplayLink *)playLink
{
    // 累加方法执行的次数
    _performTimes ++;
    if (_lastTimestamp == 0) {
        _lastTimestamp = playLink.timestamp;
        return;
    }
    // 记录执行的时间
    NSTimeInterval interval = playLink.timestamp - _lastTimestamp;
    // 当时间经过一秒的时候再计算FPS,否则计算的太过频繁
    if (interval >= 1) {
        // 执行次数/时间(iOS正常刷新率为每秒60次)
        float fps = _performTimes / interval;
        // 重新初始化记录值
        _performTimes = 0;
        _lastTimestamp = playLink.timestamp;
        NSLog(@"FPS:%f",fps);
    }
}

2019-08-19 16:35:19.599948+0800 FPS检测[3014:152429] FPS:59.720940
2019-08-19 16:35:20.599965+0800 FPS检测[3014:152429] FPS:59.720940
2019-08-19 16:35:21.599976+0800 FPS检测[3014:152429] FPS:59.720940
2019-08-19 16:35:22.600040+0800 FPS检测[3014:152429] FPS:59.720940
2019-08-19 16:35:23.600051+0800 FPS检测[3014:152429] FPS:59.720936
2019-08-19 16:35:24.600025+0800 FPS检测[3014:152429] FPS:59.720936
2019-08-19 16:35:25.600067+0800 FPS检测[3014:152429] FPS:59.720936
2019-08-19 16:35:26.600079+0800 FPS检测[3014:152429] FPS:59.720932
2019-08-19 16:35:27.600086+0800 FPS检测[3014:152429] FPS:59.720932
2019-08-19 16:35:28.600099+0800 FPS检测[3014:152429] FPS:59.720932
2019-08-19 16:35:29.600108+0800 FPS检测[3014:152429] FPS:59.720928
2019-08-19 16:35:30.599178+0800 FPS检测[3014:152429] FPS:59.720928
2019-08-19 16:35:31.600122+0800 FPS检测[3014:152429] FPS:59.720928
2019-08-19 16:35:32.599592+0800 FPS检测[3014:152429] FPS:59.720924
2019-08-19 16:35:33.600135+0800 FPS检测[3014:152429] FPS:59.720924
2019-08-19 16:35:34.598996+0800 FPS检测[3014:152429] FPS:59.720924
2019-08-19 16:35:35.599096+0800 FPS检测[3014:152429] FPS:59.720921
2019-08-19 16:35:36.600101+0800 FPS检测[3014:152429] FPS:59.720921
2019-08-19 16:35:37.600027+0800 FPS检测[3014:152429] FPS:59.720921
2019-08-19 16:35:38.600190+0800 FPS检测[3014:152429] FPS:59.720921
2019-08-19 16:35:39.599377+0800 FPS检测[3014:152429] FPS:59.720917
2019-08-19 16:35:40.599351+0800 FPS检测[3014:152429] FPS:59.720917

或者可以直接用第三方框架 YYFPSLabel
就是采用这个原理做的

屏幕快照 2019-08-19 下午5.58.50.png
上一篇下一篇

猜你喜欢

热点阅读