CADisplayLink
講道理一秒是執(zhí)行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];