6

I have an app using an NSTimer at centisecond (0.01 second) update intervals to display a running stopwatch in String Format as 00:00.00 (mm:ss.SS). (Basically cloning the iOS built-in stopwatch to integrate into realtime sports timing math problems, possibly needing millisecond accuracy in the future)

I use (misuse?) the NSTimer to force-update the UILabel. If the user presses Start, this is the NSTimer code used to start repeating the function:

displayOnlyTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("display"), userInfo: nil, repeats: true)

And here is the function that is executed by the above NSTimer:

func display() {
    let currentTime = CACurrentMediaTime() - timerStarted + elapsedTime

    if currentTime < 60 {
        timeDisplay.text = String(format: "%.2f", currentTime)
    }else if currentTime < 3600 {
        var minutes = String(format: "%00d", Int(currentTime/60))
        var seconds = String(format: "%05.2f", currentTime % 60)
        timeDisplay.text =  minutes + ":" + seconds
    }else {
        var hours = String(format: "%00d", Int(currentTime/3600))
        var minutes = String(format: "%02d", (Int(currentTime/60)-(Int(currentTime/3600)*60)))
        var seconds = String(format: "%05.2f", currentTime % 60)
        timeDisplay.text =  hours + ":" + minutes + ":" + seconds
    }
}

There will be at least 2 display links running at the same time. Will this method be too inefficient once all other elements are in play?

The display is then updated without using NSTimer when the user presses stop/pause/reset. I didn't find anything that directly translated into Swift. I'm fairly certain I'm using an inefficient method to force update the text UILabel quickly in the UIView.

More Details: I'm working on less messy code for the running timer format (mm:ss.SS). I will update this once more when I've finished that.

UPDATE: Thanks to Rob and jtbandes for answering both of my questions (formatting method and display update method). It was easy to replace the NSTimer (see above) with CADisplayLink():

displayLink = CADisplayLink(target: self, selector: Selector("display"))
        displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)

And then replace all instances in code of

displayOnlyTimer.invalidate() 

with

displayLink.paused = true 

(this will pause the display link from updating)

8
  • Just for my own peace of mind, you weren't creating a new NSDateFormatter every time, were you? As in, you weren't creating your NSDateFormatter instance inside the display() method, correct? Jul 13, 2015 at 4:25
  • jtbandes is right and you should accept that answer (use display link and not timer; definitely don't call CACurrentMediaTime multiple times within the function ... it could have ticked over to the next minute between one call and the next, resulting in output that's entirely wrong; if you use formatter, instantiate it once and reuse it; etc.). By the way, if you're going to do it like you've done above, rather than figuring out whether you're greater than 10 or not, just use a format string like %05.2f (which will format it as xx.xx, with leading zero).
    – Rob
    Jul 13, 2015 at 4:36
  • Thankfully no. I save the start time to a variable when the user presses a number. When they pause it I just subtracts the start time from CACurrentMediaTime() and adds it to the running total.
    – mothy
    Jul 14, 2015 at 5:48
  • Also, I've tried to add "%00.2f" and "%02.2f" and every other combination I could find but was not successful in getting a zero before digits lower than 10. I'll try again tomorrow. I was starting to wonder if it is a current Swift issue.
    – mothy
    Jul 14, 2015 at 6:04
  • 1
    Sorry, I'm a total noob. Only been coding seriously for a few weeks and not familiar with this site. I accepted it. Thank you for the tip.
    – mothy
    Jul 22, 2015 at 17:40

2 Answers 2

7

For rapid UI updates you should use a CADisplayLink. Anything faster than the display refresh rate is a waste of processing power since it physically cannot be displayed. It also provides a timestamp of the previous frame so you can try to predict when the next frame will be.

You're calculating CACurrentMediaTime() - timerStarted + elapsedTime multiple times. I would recommend doing it only once and saving it in a local variable.

Consider using NSDateComponentsFormatter. Try to reuse one instance of the formatter rather than creating a new one each time (which is usually the most expensive part). Overall, the less string manipulation you can do, the better.

You can check CACurrentMediaTime at the beginning and end of your display method to see how long it takes. Ideally it should be much less than 16.6ms. Keep an eye on the CPU usage (and general power consumption) in the Xcode debug navigator.

6
  • Thank you very much. Correct me if I'm wrong but I can't actually use a variable with CACurrentMediaTime() because calling the variable wouldn't update the variable to the current time, it would be the time at which the variable was first saved. But then again, answering that might be useless, assuming that CADisplayLink works much differently than my current code when I look it up tomorrow.
    – mothy
    Jul 14, 2015 at 5:58
  • 1
    Correct, but the point is that within the one function, it's better to say let currentTime = CACurrentMediaTime() and reuse that than to call it repeatedly.
    – jtbandes
    Jul 14, 2015 at 6:00
  • Yeah it didn't look right to me, that makes sense now. It's getting called at the very least 2x even if the first statement is true. One last question: If I called it as a constant let variable, is that still safe to use since the value of CACurrentMediaTime() is a different value every time the function is called? AKA does the variable let cease to exist once the function is completed?
    – mothy
    Jul 14, 2015 at 17:14
  • Not entirely sure I understand the question, but if you're asking "how do variables work", I can only point you to the documentation. It's a very broad question.
    – jtbandes
    Jul 14, 2015 at 20:00
  • 1
    Sure the value of CACurrentMediaTime() will be different every time if you call it multiple times in a row. That's exactly the reason why I suggest you store it once at the beginning of the function. Since you're trying to do multiple checks (< 60, < 3600, etc.) on the same expression, you really don't want it to change while you're doing those. Also again would recommend NSDateComponentsFormatter over manual formatting if you can swing it.
    – jtbandes
    Jul 16, 2015 at 6:47
1

I was solving the same problem today and found this answer. The Rob's and jtbandes' advices are helped a lot and i was able to assemble the clean and working solution from around the internet. Thanks you guys. And thanks to mothy for the question.

I've decided to use CADisplayLink because there is no point in firing timer's callback more often than the screen updates:

class Stopwatch: NSObject {
    private var displayLink: CADisplayLink!
    //...

    override init() {
        super.init()

        self.displayLink = CADisplayLink(target: self, selector: "tick:")
        displayLink.paused = true
        displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
        //...
    }
    //...
}

I'm tracking time by incrementing the elapsedTime variable by displayLink.duration each tick:

var elapsedTime: CFTimeInterval!

override init() {
    //...
    self.elapsedTime = 0.0
    //...
}

func tick(sender: CADisplayLink) {
    elapsedTime = elapsedTime + displayLink.duration
    //...
}

Time-formatting is done through NSDateFormatter:

private let formatter = NSDateFormatter()

override init() {
//...
        formatter.dateFormat = "mm:ss,SS"
}

func elapsedTimeAsString() -> String {
        return formatter.stringFromDate(NSDate(timeIntervalSinceReferenceDate: elapsedTime))
}

The UI can be updated in the callback closure which Stopwatch calls on every tick:

var callback: (() -> Void)?

func tick(sender: CADisplayLink) {
    elapsedTime = elapsedTime + displayLink.duration

    // Calling the callback function if available
    callback?()
}

And that's all you need to do in the ViewController to utilize the Stopwatch:

let stopwatch = Stopwatch()
stopwatch.callback = self.tick

func tick() {
   elapsedTimeLabel.text = stopwatch.elapsedTimeAsString()
}

Here is the gist with the full code of Stopwatch and usage guide: https://gist.github.com/Flar49/06b8c9894458a3ff1b14

I hope that this explanation and gist will help others who will stumble upon this thread in the future with the same problem :)

1
  • Do you have an equivalent version for OS X?
    – Matt
    Jul 19, 2016 at 6:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.