Accurate timing in iOS

后端 未结 7 1360
生来不讨喜
生来不讨喜 2020-12-01 02:32

I am looking at the \'Metronome\' sample code from the iOS SDK (http://developer.apple.com/library/ios/#samplecode/Metronome/Introduction/Intro.html). I am running the metro

相关标签:
7条回答
  • 2020-12-01 03:09

    If you need <100msec precision, look into CADisplayLink. It calls a selector at regular intervals, as fast as 60 times a second, i.e. every .0166667 sec.

    If you want to do your metronome test, you'd set frameInterval to 60 so it gets called back once a second.

    self.syncTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(syncFired:)];
    self.syncTimer.frameInterval = 60;
    [self.syncTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
    -(void)syncFired:(CADisplayLink *)displayLink
    {
        static NSTimeInterval lastSync = 0;
        NSTimeInterval now = CACurrentMediaTime();
        if (lastSync > 0) {
            NSLog(@"interval: %f", now - lastSync);
        }
        lastSync = now;
    }
    

    In my tests, that timer is called consistently every second within 0.0001 sec.

    On the off chance you're running on a device with a different refresh rate than 60Hz, you'd have to divide displayLink.duration into 1.0 and round to the nearest integer (not the floor).

    0 讨论(0)
提交回复
热议问题