Reputation: 67
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.
Upvotes: 1
Views: 472
Reputation: 181
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)
Upvotes: 0
Reputation: 154583
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]
Upvotes: 3
Reputation: 1909
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
}
}
Upvotes: 1