iOS-利用CADisplayLink计算FPS

CADisplayLink会在每次刷新屏幕的时候,执行Delegate,从而计算出FPS,检测CPU的卡顿。

注意,需要加入到RunLoop中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#import <SpriteKit/SpriteKit.h>

_link = [CADisplayLink displayLinkWithTarget:self selector:@selector(tick:)];
[_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];

CFTimeInterval lastTime = 0;
int count = 0;
- (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;

NSLog(@"FPS::%d", (int)round(fps));
}

运行结果如下:

1
2
3
4
5
6
FPS::59
FPS::60
FPS::60
FPS::60
FPS::60
FPS::60

单独使用CADisplayLink,只能检测CPU的FPS,对于GPU长时间进行视图混合造成的卡顿,无法检测,因此引入一个空像素点的SKView, 当GPU出现卡顿时,依然会触发CADisplayLink回调。

1
2
3
4
SKScene *scene = [SKScene new];
_sceneView = [[SKView alloc] initWithFrame:CGRectMake(0.0, 0.0, 1.0, 1.0)];
[_sceneView presentScene:scene];
[[UIApplication sharedApplication].keyWindow addSubview:sceneView];