iPhone:如何获得当前毫秒?

219 iphone time timestamp ios current-time

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

小智 307

如果您正在考虑将其用于相对时间(例如游戏或动画),我宁愿使用CACurrentMediaTime()

double CurrentTime = CACurrentMediaTime();
Run Code Online (Sandbox Code Playgroud)

这是推荐的方式; NSDate从网络同步时钟中抽取,并在将其与网络重新同步时偶尔打嗝.

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


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

let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)
Run Code Online (Sandbox Code Playgroud)

  • 哎呀 - 那导入#import <QuartzCore/CAAnimation.h> (8认同)
  • 但似乎需要两倍的时间[[NSDate date] timeIntervalSince1970].我在15000次通话中测量了0.065ms与0.033ms. (6认同)
  • 对于Xcode的新手(像我一样),"包含Quartz Framework"意味着将它添加到"Link Binary With Libraries"中的库集. (6认同)
  • 如果有人在寻找与SpriteKit相关的内容,那么SKScene的更新方法中的"当前时间"确实是CACurrentMediaTime(); (3认同)
  • 重要提示: CACurrentMediaTime() 在设备休眠时不会滴答滴答! (3认同)

cod*_*gic 271

[[NSDate date] timeIntervalSince1970];
Run Code Online (Sandbox Code Playgroud)

它将自纪元以来的秒数作为双精度返回.我几乎可以肯定你可以从小数部分访问毫秒.

  • "那些括号"是客观的.如果你想为iOS开发,你应该对它们感到满意. (116认同)
  • 它不会像以下那样杀死任何人:NSTimeInterval myInterval = NSDate.timeIntervalSince1970; //如果你问我,所有这些括号都是老式的. (28认同)
  • 根据http://stackoverflow.com/q/11474284/209828,"这些括号"是语法的较新版本 (11认同)
  • `[NSDate timeIntervalSinceReferenceDate]`更便宜.(虽然它引用了一个不同的"时代" - 如果你想要1970年添加常量`NSTimeIntervalSince1970`.) (5认同)
  • 我已经使用这种方法一段时间了,并且意识到它可以在几毫秒之后调用它时返回一个更早的值(例如,连续调用它并且你可能不会以增加的顺序结束) (4认同)
  • @Satyam实际上乘以1000将为您提供毫秒精度,根据文档,`timeIntervalSince1970`返回的TimeInterval实际上是具有“亚毫秒精度”的Double。 (2认同)

dar*_*inm 90

我在iPhone 4S和iPad 3(发布版本)上对所有其他答案进行了基准测试.CACurrentMediaTime具有较小的开销.timeIntervalSince1970比其他人慢得多,可能是由于NSDate实例化开销,尽管对许多用例来说可能并不重要.

我建议CACurrentMediaTime如果你想要最少的开销,不介意添加Quartz Framework依赖项.或者gettimeofday如果可移植性是您的首要任务.

iPhone 4S

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

  • 请注意这个问题:http://bendodson.com/weblog/2013/01/29/ca-current-media-time/当设备进入睡眠状态时,此时钟显然会停止. (2认同)

Raj*_*ari 51

在Swift中我们可以创建一个函数并执行如下操作

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

var currentTime = getCurrentMillis()
Run Code Online (Sandbox Code Playgroud)

虽然它的做工精细的雨燕3.0,但我们可以通过修改和使用Date类,而不是NSDate3.0

Swift 3.0

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

var currentTime = getCurrentMillis()
Run Code Online (Sandbox Code Playgroud)


小智 30

到目前为止,我gettimeofday在iOS(iPad)上找到了一个很好的解决方案,当你想要执行一些间隔评估时(比如帧率,渲染帧的时间......):

#include <sys/time.h>
struct timeval time;
gettimeofday(&time, NULL);
long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个,因为它非常便携.请注意,根据操作系统,您可能需要使用"long long"而不是"long",同样在执行其余计算之前将time.tv_sec转换为"long long". (2认同)

Raj*_*han 18

获取当前日期的毫秒数.

斯威夫特4:

func currentTimeInMilliSeconds()-> Int
    {
        let currentDate = Date()
        let since1970 = currentDate.timeIntervalSince1970
        return Int(since1970 * 1000)
    }
Run Code Online (Sandbox Code Playgroud)


que*_*ful 17

斯威夫特2

let seconds = NSDate().timeIntervalSince1970
let milliseconds = seconds * 1000.0
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds
Run Code Online (Sandbox Code Playgroud)

  • `TimeInterval`又名`Double`没有毫秒属性.`Date().timeIntervalSince1970*1000` (2认同)

Tyl*_*ler 10

了解CodeTimestamps可能很有用,它提供了基于mach的定时函数的包装器.这为您提供纳秒分辨率的定时数据 - 比毫秒更精确1000000倍.是的,精确度要高出一百万倍.(前缀是milli,micro,nano,每个都比上一个精确1000倍.)即使你不需要CodeTimestamps,也要查看代码(它的开源代码),看看他们如何使用mach来获取时序数据.当您需要更高的精度并希望比NSDate方法更快的方法调用时,这将非常有用.

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

  • 从页面链接的源代码在这里:https://github.com/tylerneylon/moriarty (3认同)

小智 8

// Timestamp after converting to milliseconds.

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


mma*_*ckh 7

我需要一个NSNumber包含确切结果的对象[[NSDate date] timeIntervalSince1970].由于这个函数被多次调用,而我真的不需要创建一个NSDate对象,因此性能并不高.

因此,要获得原始函数给我的格式,请尝试以下方法:

#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv,NULL);
double perciseTimeStamp = tv.tv_sec + tv.tv_usec * 0.000001;
Run Code Online (Sandbox Code Playgroud)

哪个应该给你完全相同的结果 [[NSDate date] timeIntervalSince1970]


Ind*_*ore 5

CFAbsoluteTimeGetCurrent()

绝对时间以秒为单位,相对于绝对参考日期 2001 年 1 月 1 日 00:00:00 GMT。正值表示参考日期之后的日期,负值表示参考日期之前的日期。例如,绝对时间-32940326 相当于1999 年12 月16 日17:54:34。重复调用此函数并不能保证结果单调递增。由于与外部时间参考同步或由于用户显式更改时钟,系统时间可能会减少。


Ren*_*Pet 5

这与@TristanLorach 发布的答案基本相同,只是为 Swift 3 重新编码:

   /// Method to get Unix-style time (Java variant), i.e., time since 1970 in milliseconds. This 
   /// copied from here: http://stackoverflow.com/a/24655601/253938 and here:
   /// http://stackoverflow.com/a/7885923/253938
   /// (This should give good performance according to this: 
   ///  http://stackoverflow.com/a/12020300/253938 )
   ///
   /// Note that it is possible that multiple calls to this method and computing the difference may 
   /// occasionally give problematic results, like an apparently negative interval or a major jump 
   /// forward in time. This is because system time occasionally gets updated due to synchronization 
   /// with a time source on the network (maybe "leap second"), or user setting the clock.
   public static func currentTimeMillis() -> Int64 {
      var darwinTime : timeval = timeval(tv_sec: 0, tv_usec: 0)
      gettimeofday(&darwinTime, nil)
      return (Int64(darwinTime.tv_sec) * 1000) + Int64(darwinTime.tv_usec / 1000)
   }
Run Code Online (Sandbox Code Playgroud)