Measuring Time Accurately in Swift for Comparison Across Devices

后端 未结 3 2091
暗喜
暗喜 2020-12-09 14:17

I need to be able to record reaction time, from when the screen loads or the question label refreshes until the user taps a number button. I\'m not finding documentation fro

3条回答
  •  旧时难觅i
    2020-12-09 14:43

    You can use NSTimeInterval to measure time (much better than a timer). You just need to store two dates (two points in time) and subtract endTime - StartTime as follow:

    import UIKit
    
    class ViewController: UIViewController {
    
        var startTime: TimeInterval = 0
        var endTime: TimeInterval = 0
    
        override func viewDidLoad() {
            super.viewDidLoad()
            startTime = Date().timeIntervalSinceReferenceDate
        }
    
        @IBAction func stopTimeAction(_ sender: Any) {
            endTime = Date().timeIntervalSinceReferenceDate
            print((endTime-startTime).time)
        }
    
    }
    

    extension TimeInterval {
        var time: String { .init(format: "%d:%02d:%02d.%03d", Int(self/3600),
                            Int((self/60).truncatingRemainder(dividingBy: 60)),
                            Int(truncatingRemainder(dividingBy: 60)),
                            Int((self*1000).truncatingRemainder(dividingBy: 1000))) }
    }
    

提交回复
热议问题