由于想统计一下动画增加时对性能的影响,就写了几个小函数,用于获取FPS.
- PS:看过一个FPSLabel的例子,里面用了几个类来实现,虽然功能看起来很多,但那些不相干功能封装在一起我认为严重不合理,特别是动不动就实例化,我极反感,根本不需要消耗内存的事情为什么要实例化.
- FPS全局只需要一个,其它地方只需要获取一下当前FPS就好了,最大化减少资源消耗.
- 在获取FPS前调用一下
fpsStart()
进行初始化,然后不断调用getFpsCount()
就是FPS了
static CADisplayLink *gs_fpsLink = nil;
static size_t gs_fpsCount = 0;
void fpsStart()
{
if (gs_fpsLink) return;
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:[IOSUtils class] selector:@selector(fpsTick:)];
[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
gs_fpsLink = link;
}
size_t getFpsCount()
{
return gs_fpsCount;
}
void fpsStop()
{
[gs_fpsLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
gs_fpsLink = nil;
}
@implementation IOSUtils
+ (void)fpsTick:(CADisplayLink *)link
{
static size_t _count = 0;
static NSTimeInterval _lastTime = 0;
if (_lastTime == 0) {
_lastTime = link.timestamp;
return;
}
_count++;
NSTimeInterval delta = link.timestamp - _lastTime;
if (delta < 1) return;
_lastTime = link.timestamp;
double fps = _count / delta;
_count = 0;
gs_fpsCount = (size_t)round(fps);
}
@end