關于CADisplayLink
A CADisplayLink object is a timer object that allows your application to synchronize its drawing to the refresh rate of the display.這是官方文檔對于CADisplayLink的定義顽耳,意思就是說CADisplayLink是一個定時器(但并不繼承自NSTimer),它能夠讓你的應用以屏幕刷新的幀率來同步更新UI,所以我們可以通過它1s內調用指定target的指定方法的次數來獲得屏幕刷新的幀率趾代,從而來判斷CPU的運行狀態(tài)。
使用
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[CPUFpsLabel setupOnView:[[application windows] firstObject].rootViewController.view];
return YES;
}
CPUFpsLabel
@interface CPUFpsLabel : UILabel
+ (void)setupOnView:(UIView *)view;
- (void)start;
@end
@implementation CPUFpsLabel
{
CADisplayLink *_link;
NSUInteger _count;
NSTimeInterval _lastTime;
}
+ (void)setupOnView:(UIView *)view
{
CGSize screenSize = [UIScreen mainScreen].bounds.size;
CPUFpsLabel *fpsLabel = [[CPUFpsLabel alloc] initWithFrame:CGRectMake(screenSize.width / 2.0 + 25, 0, 50, 20)];
[fpsLabel start];
[view addSubview:fpsLabel];
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.font=[UIFont boldSystemFontOfSize:12];
self.textColor=[UIColor colorWithRed:0.33 green:0.84 blue:0.43 alpha:1.00];
self.backgroundColor=[UIColor clearColor];
self.textAlignment = NSTextAlignmentCenter;
_link = [CADisplayLink displayLinkWithTarget:self selector:@selector(tick:)];
[_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
_link.paused = YES;
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(applicationDidBecomeActiveNotification)
name: UIApplicationDidBecomeActiveNotification
object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(applicationWillResignActiveNotification)
name: UIApplicationWillResignActiveNotification
object: nil];
}
return self;
}
- (void)dealloc
{
[_link invalidate];
[_link removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
- (void)applicationDidBecomeActiveNotification
{
[_link setPaused:NO];
}
- (void)applicationWillResignActiveNotification
{
[_link setPaused:YES];
}
- (void)start
{
[_link setPaused:NO];
}
- (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;
NSString *fpsString = [NSString stringWithFormat:@"%zd fps",(int)round(fps)];
self.text = fpsString;
}
@end