美文网首页
12-1 iOS 记录FPS

12-1 iOS 记录FPS

作者: Rumbles | 来源:发表于2020-10-18 08:24 被阅读0次

    CADisplayLink

    讲道理一秒是执行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];
    

    相关文章

      网友评论

          本文标题:12-1 iOS 记录FPS

          本文链接:https://www.haomeiwen.com/subject/lbyytctx.html