原理:CADisplayLink是在每一帧绘制之前调用,并且可以获取时间戳。

1 – (void)viewDidLoad {
2     [super viewDidLoad];
3
4     _lastTimestamp = -1;
5     _frameCount = 0;
6     CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(calFPS:)];
7     [link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
8 }
9
10 //计算1S内帧数
11 -(void)calFPS:(CADisplayLink *)displayLink
12 {
13     if(_lastTimestamp == -1){
14         _lastTimestamp = displayLink.timestamp;
15         return;
16     }
17
18     _frameCount++;
19
20     NSTimeInterval interval = displayLink.timestamp – _lastTimestamp;
21
22     if(interval < 1){
23         return;
24     }
25
26     _lastTimestamp = displayLink.timestamp;
27
28     CGFloat fps = _frameCount / interval;
29
30     NSLog(@”%f”, fps);
31
32     _frameCount = 0;
33 }