Skip to content

Instantly share code, notes, and snippets.

@marslin1220
Created February 21, 2020 08:18
Show Gist options
  • Save marslin1220/3b0c29e70a6c017a9fc117323a25b8e0 to your computer and use it in GitHub Desktop.
Save marslin1220/3b0c29e70a6c017a9fc117323a25b8e0 to your computer and use it in GitHub Desktop.
import Foundation
class FrameTimeintervalCollector {
private(set) lazy var displayLink: CADisplayLink = { //< 1.
let displayLink = CADisplayLink(target: self, selector: #selector(tick(displayLink:)))
displayLink.add(to: .main, forMode: .default)
return displayLink
}()
private(set) var frameTickTimeSet = Set<FrameTickTime>() //< 2.
private var lastTimestamp: TimeInterval = 0
private let serialQueue = DispatchQueue(label: "frameTickQueue")
init() {
displayLink.isPaused = false
}
@objc private func tick(displayLink: CADisplayLink) {
serialQueue.async { //< 3.
guard self.lastTimestamp != 0 else {
self.lastTimestamp = displayLink.timestamp
return
}
let frameTimeinterval = displayLink.timestamp - self.lastTimestamp
self.lastTimestamp = displayLink.timestamp
self.frameTickTimeSet.insert(FrameTickTime(frameTimeinterval: frameTimeinterval))
}
}
func reset() {
frameTickTimeSet.removeAll()
}
}
struct FrameTickTime: Hashable {
let frameTimeinterval: TimeInterval
let date: Date = Date()
}
enum FPSMetricError: Error {
case frameTickTimeIsEmpty
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment