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


当前回答

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/

其他回答

我在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
[[NSDate date] timeIntervalSince1970];

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

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

double CurrentTime = CACurrentMediaTime();

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

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


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

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

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

// Timestamp after converting to milliseconds.

NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];