I am making a live stream of current time with this code:
let timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { timer in
print(self.time())
}
func time() -> String {
let date = Date()
let calendar = Calendar.current
let hour: Int = calendar.component(.hour, from: date)
let minutes: Int = calendar.component(.minute, from: date)
let second: Int = calendar.component(.second, from: date)
return String(describing: hour) + ":" + String(describing: minutes) + ":" + String(describing: second)
}
The output would be:
16:28:21
16:28:21
16:28:21
16:28:21
16:28:21
16:28:22
16:28:22
16:28:22
16:28:22
16:28:22
16:28:23
16:28:23
16:28:23
16:28:23
16:28:23
16:28:24
As you can see my codes are not good enough to be efficient, because I calculate 16:28:21 five times which could be done just with 1 call, if I would make my codes more efficient then I have to bring my timer interval near to 1 but that make my codes not precise to telling the real and correct time, if I keep using 0.2 for timer interval I also have an inaccuracy of 0.2 sec so what should I do?
If I want my codes be more precise than what it is, then probably I have to use 0.01 for timer interval with that said I would have an inaccuracy of 0.01 sec of real time and also so many unnecessary calls for reading the current time.
So how can I solve this issue that my code be real sharp in telling correct current time meanwhile not putting so many load for cpu.
Update:
func nextRead() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss.SS"
let diff = 1_000_000_000 - Calendar.current.component(.nanosecond, from: .now)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.nanoseconds(diff)) {
print(dateFormatter.string(from: .now), diff)
nextRead()
}
}
output:
00:23:44.04 841395021
00:23:45.04 956941963
00:23:46.04 954411030
00:23:47.04 953773976
00:23:48.04 953575969
00:23:49.04 954488040
00:23:50.04 954362989
00:23:51.04 954159022
00:23:52.01 954460979
00:23:53.04 981551052
00:23:54.04 950816989