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


当前回答

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/

其他回答

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/

在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()

如果你不想包含Quartz框架,[NSDate timeintervalsincerely eferencedate]是另一个选项。它返回一个double,表示秒数。

如果你正在考虑使用这个相对定时(例如游戏或动画),我宁愿使用CACurrentMediaTime()

double CurrentTime = CACurrentMediaTime();

哪一种是推荐的方式;NSDate从网络的同步时钟中提取,并且在与网络重新同步时偶尔会打嗝。

它返回当前的绝对时间,以秒为单位。


如果你只想要小数部分(通常在同步动画时使用),

let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)

这是我给斯威夫特用的

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

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

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