简体   繁体   中英

how to calculate time between receiving variables in swift

I have a variable that will changes every millisecond or so. I want to calculate the time between them correctly without delay.

I want to know how long takes to get the new one.

Is that possible in swift? I know that there is a timer in swift but according to apple documentation:

that's not exact.i need to get the millisecond time between each receiving variable.

Use a property observer didSet with Date arithmetic to compute the interval between changes.

Here is an example:

class ViewController: UIViewController {

    private var setTime: Date?
    private var intervals = [Double]()

    var value: Int = 0 {
        didSet {
            let now = Date()
            if let previous = setTime {
                intervals.append(now.timeIntervalSince(previous) * 1000)
            }
            setTime = now
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        for i in 1...20 {
            value = i
        }

        print(intervals)
    }

}

Console output

[0.0020265579223632812, 0.12600421905517578, 0.00095367431640625, 0.0050067901611328125, 0.0010728836059570312, 0.00095367431640625, 0.00095367431640625, 0.0010728836059570312, 0.00095367431640625, 0.0020265579223632812, 0.00095367431640625, 0.0010728836059570312, 0.00095367431640625, 0.0, 0.0010728836059570312, 0.00095367431640625, 0.00095367431640625, 0.0020265579223632812, 0.0010728836059570312]

You can capture time whenever the value changes and calculate the difference. like:

var yourVar: Int {
    willSet {
        //you can capture the time here
    }

    didSet {
        //or here
    }
}
var _variable = 0
var variable : Int {
    get{
        return _variable
    }
    set{
        let start = DispatchTime.now()
        _variable = newValue
        let dst = start.distance(to: DispatchTime.now())
        print("Interval = \(dst)")
    }
}

variable = 1
variable = 2

Output:
Interval = nanoseconds(2239301) Interval = nanoseconds(69482)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM