[英]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:
我知道swift中有一个计时器,但根据苹果文档:
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. 使用属性观察器
didSet
with Date
算法来计算更改之间的间隔。
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]
[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) 间隔=纳秒(2239301)间隔=纳秒(69482)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.