【问题标题】:iPhone: How to get current milliseconds?iPhone:如何获得当前的毫秒数?
【发布时间】:2010-09-26 08:54:24
【问题描述】:

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

【问题讨论】:

    标签: ios iphone time timestamp current-time


    【解决方案1】:

    获取当前日期的毫秒数。

    Swift 4+:

    func currentTimeInMilliSeconds()-> Int
        {
            let currentDate = Date()
            let since1970 = currentDate.timeIntervalSince1970
            return Int(since1970 * 1000)
        }
    

    【讨论】:

      【解决方案2】:
      let timeInMiliSecDate = Date()
      let timeInMiliSec = Int (timeInMiliSecDate.timeIntervalSince1970 * 1000)
      print(timeInMiliSec)
      

      【讨论】:

      • 请在您的代码中添加一些解释,以便其他人可以从中学习 - 特别是如果您发布一个已经有很多赞成答案的问题的答案
      【解决方案3】:
       func currentmicrotimeTimeMillis() -> Int64{
      let nowDoublevaluseis = NSDate().timeIntervalSince1970
      return Int64(nowDoublevaluseis*1000)
      

      }

      【讨论】:

        【解决方案4】:
        NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); //double
        long digits = (long)time; //first 10 digits        
        int decimalDigits = (int)(fmod(time, 1) * 1000); //3 missing digits
        /*** long ***/
        long timestamp = (digits * 1000) + decimalDigits;
        /*** string ***/
        NSString *timestampString = [NSString stringWithFormat:@"%ld%03d",digits ,decimalDigits];
        

        【讨论】:

          【解决方案5】:

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

          double CurrentTime = CACurrentMediaTime();
          

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

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


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

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

          【讨论】:

          • 但是 [[NSDate date] timeIntervalSince1970] 所需的时间似乎是原来的两倍。我在 15000 次调用中测量了 0.065 毫秒与 0.033 毫秒。
          • 哎呀-这就是导入#import
          • 对于那些刚接触 Xcode 的人(比如我),“包含 Quartz 框架”意味着将其添加到“Link Binary With Libraries”中的库集合中。
          • 如果有人正在寻找与 SpriteKit 相关的这个,SKScene 的更新方法中的“当前时间”确实是 CACurrentMediaTime();
          • 重要提示:CACurrentMediaTime() 在设备休眠时没有计时!
          【解决方案6】:

          斯威夫特 2

          let seconds = NSDate().timeIntervalSince1970
          let milliseconds = seconds * 1000.0
          

          斯威夫特 3

          let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds
          

          【讨论】:

          • TimeInterval aka Double 没有毫秒属性。 Date().timeIntervalSince1970 * 1000
          【解决方案7】:

          这与@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)
             }
          

          【讨论】:

            【解决方案8】:

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

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

            虽然它在 Swift 3.0 中运行良好,但我们可以在 3.0 中修改和使用 Date 类而不是 NSDate

            Swift 3.0

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

            【讨论】:

              【解决方案9】:

              试试这个:

              NSDate * timestamp = [NSDate dateWithTimeIntervalSince1970:[[NSDate date] timeIntervalSince1970]];
              
              NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
              [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss.SSS"];
              
              NSString *newDateString = [dateFormatter stringFromDate:timestamp];
              timestamp = (NSDate*)newDateString;
              

              在此示例中,dateWithTimeIntervalSince1970 与格式化程序 @"YYYY-MM-dd HH:mm:ss.SSS" 组合使用,它将返回带有年、月、日的日期和带有小时、分钟、秒的时间, 和毫秒。请参阅示例:“2015-12-02 04:43:15.008”。我使用 NSString 来确保格式之前已经写入。

              【讨论】:

                【解决方案10】:

                这是我在 Swift 中使用的

                var date = NSDate()
                let currentTime = Int64(date.timeIntervalSince1970 * 1000)
                
                print("Time in milliseconds is \(currentTime)")
                

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

                【讨论】:

                  【解决方案11】:

                  CFAbsoluteTimeGetCurrent()

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

                  【讨论】:

                    【解决方案12】:
                    [[NSDate date] timeIntervalSince1970];
                    

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

                    【讨论】:

                    • 我使用这个方法已经有一段时间了,当你在几毫秒后调用它时,我意识到它可以返回一个更早的值(例如连续调用它,你可能不会以增加序列)
                    • [NSDate timeIntervalSinceReferenceDate] 更便宜。 (虽然它引用了一个不同的“纪元”——如果你想要 1970 年添加常量 NSTimeIntervalSince1970。)
                    • timeIntervalSince1970 是一个实例属性,而不是 NSDate 上的静态方法。所以仍然必须写 NSTimeInterval myInterval = [NSDate date].timeIntervalSince1970 !!
                    • 以毫秒为单位 CurrentTime = [[NSDate date] timeIntervalSince1970] * 1000;
                    • @Satyam 实际上乘以 1000 将为您提供毫秒精度,根据文档,timeIntervalSince1970 返回的 TimeInterval 实际上是具有“亚毫秒精度”的 Double。
                    【解决方案13】:
                    // Timestamp after converting to milliseconds.
                    
                    NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];
                    

                    【讨论】:

                      【解决方案14】:

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

                      如果您想要最少的开销并且不介意添加 Quartz 框架依赖项,我建议您使用 CACurrentMediaTime。或者 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
                      

                      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
                      

                      【讨论】:

                      • +1,虽然这显然内容丰富且很有帮助,但如果没有看到一些源代码,我不会完全称其为伟大的工程工作;)
                      • 请注意这个问题:bendodson.com/weblog/2013/01/29/ca-current-media-time 当设备进入睡眠状态时,这个时钟显然会停止。
                      • NSTimeIntervalSince1970这个最快的宏。
                      • @ozgur NSTimeIntervalSince1970 是一个常量,描述 1970-01-01 和“参考日期”(即 2001-01-01)之间的秒数,因此它始终等于 978307200
                      【解决方案15】:

                      到目前为止,我发现 gettimeofday 在 iOS (iPad) 上是一个很好的解决方案,当您想要执行一些间隔评估(例如,帧速率、渲染帧的时间......)时:

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

                      【讨论】:

                      • 我也喜欢这个,因为它非常便携。请注意,根据操作系统的不同,您可能需要使用“long long”而不是“long”,并且在进行其余计算之前同样将 time.tv_sec 转换为“long long”。
                      • static unsigned long getMStime(void) { struct timeval time; gettimeofday(&time, NULL);返回 (time.tv_sec * 1000) + (time.tv_usec / 1000); }
                      • 有趣的是,这在我的 iPhone 5S 和 Mac 上运行良好,但在 iPad 3 上返回错误值。
                      • 为了避免得到负数,我必须在数学之前强制转换:int64_t result = ((int64_t)tv.tv_sec * 1000) + ((int64_t)tv.tv_usec / 1000);跨度>
                      • 返回时间在-ve
                      【解决方案16】:

                      我需要一个包含[[NSDate date] timeIntervalSince1970] 的确切结果的NSNumber 对象。由于这个函数被调用了很多次,而且我真的不需要创建一个NSDate 对象,所以性能不是很好。

                      所以要获得原始函数给我的格式,试试这个:

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

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

                      【讨论】:

                        【解决方案17】:

                        [NSDate timeIntervalSinceReferenceDate] 是另一种选择,如果您不想包含 Quartz 框架。它返回一个双精度值,表示秒。

                        【讨论】:

                          【解决方案18】:

                          了解 CodeTimestamps 可能会很有用,它提供了基于 mach 的计时函数的包装器。这为您提供了纳秒分辨率的计时数据 - 比毫秒精度高 1000000 倍。是的,精确到一百万倍。 (前缀是毫、微、纳米,每一个都比上一个精确 1000 倍。)即使您不需要 CodeTimestamps,也请查看代码(它是开源的),看看它们如何使用 mach 来获取计时数据。当您需要更高的精度并想要比 NSDate 方法更快的方法调用时,这将很有用。

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

                          【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2023-03-06
                          • 1970-01-01
                          相关资源
                          最近更新 更多