【发布时间】:2020-01-30 04:43:37
【问题描述】:
我正在尝试找到一种方法来判断它在几秒钟内执行一个函数需要多长时间。目前我正在这样做:
let startDate = Date()
let endDate = Date()
let calendar = Calendar.current
let dateComponents = calendar.compare(startDate, to: endDate, toGranularity: .second)
let seconds = dateComponents.rawValue
print("Seconds: \(seconds)")
但每次我打印出秒数时,它总是显示为 -1。我已经研究过这个问题:elapsed time 但我需要输出以秒为单位。有什么建议吗?
【问题讨论】:
-
compare不会告诉您两次之间的差异,它只是告诉某人您是否早于/晚于给定单位developer.apple.com/documentation/foundation/calendar/…。您链接的问题有您需要的答案;TimeInterval以秒为单位。如果您不想要分数,只需将值四舍五入到最接近的整秒 -
有多种方法可以做到这一点。许多用户发布了计时器方法等,但是如果您使用
URLSession,另一个选择是:developer.apple.com/documentation/foundation/…