12-1 iOS 记录FPS

CADisplayLink

讲道理一秒是执行60次。所以  CADisplayLink 的时间间隔是 60分之1 秒

如果卡顿。那么使用1秒 除时间间隔就可以得到帧率

简单代码

#define kSize CGSizeMake(55, 20)

@interface CJFPSLabel ()
@property (nonatomic, strong) CADisplayLink *link;
@property (nonatomic, assign) NSTimeInterval lastTime;
@property (nonatomic, assign) NSInteger count;
@end

@implementation CJFPSLabel

- (instancetype)initWithFrame:(CGRect)frame {
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size = kSize;
    }
    self = [super initWithFrame:frame];
    
    _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(tick:)];
    [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    
    return self;
}

- (void)tick:(CADisplayLink *)link {
    if (_lastTime == 0) {
        _lastTime = link.timestamp;
        return;
    }
    
    _count++;
    NSTimeInterval delta = link.timestamp - _lastTime;
    if (delta < 1) return;
    _lastTime = link.timestamp;
    float fps = _count / delta;
    _count = 0;
    
    self.text = [NSString stringWithFormat:@"%d FPS",(int)round(fps)];
}

@end

使用:
    CJFPSLabel *label = [[CJFPSLabel alloc]initWithFrame:CGRectMake(100, 0, 100, 20)];
    [self.window addSubview:label];

你可能感兴趣的:(12-1 iOS 记录FPS)