获得当前系统时间毫秒的最佳方法是什么?


当前回答

 func currentmicrotimeTimeMillis() -> Int64{
let nowDoublevaluseis = NSDate().timeIntervalSince1970
return Int64(nowDoublevaluseis*1000)

}

其他回答

It may be useful to know about CodeTimestamps, which provide a wrapper around mach-based timing functions. This gives you nanosecond-resolution timing data - 1000000x more precise than milliseconds. Yes, a million times more precise. (The prefixes are milli, micro, nano, each 1000x more precise than the last.) Even if you don't need CodeTimestamps, check out the code (it's open source) to see how they use mach to get the timing data. This would be useful when you need more precision and want a faster method call than the NSDate approach.

http://eng.pulse.me/line-by-line-speed-analysis-for-ios-apps/

[[NSDate date] timeIntervalSince1970];

它以双精度返回自epoch以来的秒数。我几乎可以肯定你可以从小数部分访问毫秒。

在Swift中,我们可以创建一个函数,并如下所示

func getCurrentMillis()->Int64{
    return  Int64(NSDate().timeIntervalSince1970 * 1000)
}

var currentTime = getCurrentMillis()

虽然它在Swift 3.0中工作得很好,但我们可以修改和使用Date类而不是3.0中的NSDate

斯威夫特3.0

func getCurrentMillis()->Int64 {
    return Int64(Date().timeIntervalSince1970 * 1000)
}

var currentTime = getCurrentMillis()

我在iPhone 4S和iPad 3(发行版本)上测试了所有其他答案。CACurrentMediaTime的开销最小。timeIntervalSince1970比其他的要慢得多,可能是由于NSDate实例化开销,尽管对于许多用例来说可能无关紧要。

如果您希望开销最少,并且不介意添加Quartz Framework依赖项,我建议您使用CACurrentMediaTime。或者gettimeofday(如果可移植性对您来说是优先考虑的)。

iPhone 4 s

CACurrentMediaTime: 1.33 µs/call
gettimeofday: 1.38 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.45 µs/call
CFAbsoluteTimeGetCurrent: 1.48 µs/call
[[NSDate date] timeIntervalSince1970]: 4.93 µs/call

iPad 3

CACurrentMediaTime: 1.25 µs/call
gettimeofday: 1.33 µs/call
CFAbsoluteTimeGetCurrent: 1.34 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.37 µs/call
[[NSDate date] timeIntervalSince1970]: 3.47 µs/call

这是我给斯威夫特用的

var date = NSDate()
let currentTime = Int64(date.timeIntervalSince1970 * 1000)

print("Time in milliseconds is \(currentTime)")

使用本网站验证准确性http://currentmillis.com/