I\'m using CADisplayLink
in my iPhone app.
Here is the relevant code:
SMPTELink = [CADisplayLink displayLinkWithTarget:self selector:@selec
Basic Swift version of the other answers (minus the animation code)
class BasicStopwatch {
var timer: CADisplayLink!
var firstTimestamp: CFTimeInterval!
var elapsedTime: TimeInterval = 0
let formatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "mm:ss.SS"
return df
}()
func begin() {
timer = CADisplayLink(target: self, selector: #selector(tick))
timer.preferredFramesPerSecond = 10 // adjust as needed
timer.add(to: .main, forMode: .common)
}
@objc func tick() {
if (self.firstTimestamp == nil) {
print("Set first timestamp")
self.firstTimestamp = timer!.timestamp
return
}
elapsedTime = timer.timestamp - firstTimestamp
/// Print raw elapsed time
// print(elapsedTime)
/// print elapsed time
print(elapsedTimeAsString())
/// If need to track frames
// let totalFrames: Double = 20
// let frameNumber = (elapsedTime * Double(timer!.preferredFramesPerSecond)).truncatingRemainder(dividingBy: totalFrames)
// print("Frame ", frameNumber)
}
func elapsedTimeAsString() -> String {
return formatter.string(from: Date(timeIntervalSinceReferenceDate: elapsedTime))
}
}
Usage
let watch = BasicStopwatch()
watch.begin()