代码之家  ›  专栏  ›  技术社区  ›  Phil

iPhone:如何获取当前毫秒数?

  •  203
  • Phil  · 技术社区  · 17 年前

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

    18 回复  |  直到 8 年前
        1
  •  264
  •   Bhavin Bhadani    10 年前
    [[NSDate date] timeIntervalSince1970];
    

    它以双精度形式返回自epoch以来的秒数。我几乎可以肯定你能从分数部分得到毫秒。

        2
  •  303
  •   Stan James nfaggian    8 年前

    如果你想把它用于相对计时(例如游戏或动画),我宁愿用它 CACurrentMediaTime()

    double CurrentTime = CACurrentMediaTime();
    

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

    它返回当前绝对时间(秒)。


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

    let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)
    
        3
  •  90
  •   devios1    11 年前

    我在iPhone4S和iPad3(发布版本)上测试了所有其他答案。 CACurrentMediaTime 开销最小,幅度很小。 timeIntervalSince1970 比其他人慢得多,可能是因为 NSDate 实例化开销,尽管对于许多用例来说并不重要。

    我建议 当前中间时间 如果您希望开销最小,并且不介意添加Quartz框架依赖项。或 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
    
        4
  •  44
  •   Rajan Maheshwari    9 年前

    在Swift中,我们可以做一个功能,如下所示

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

    尽管它在 斯威夫特3 但是我们可以修改和使用 Date 类而不是 NSDate 在里面

    斯威夫特3

    func getCurrentMillis()->Int64 {
        return Int64(Date().timeIntervalSince1970 * 1000)
    }
    
    var currentTime = getCurrentMillis()
    
        5
  •  30
  •   giampaolo    12 年前

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

    #include <sys/time.h>
    struct timeval time;
    gettimeofday(&time, NULL);
    long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);
    
        6
  •  17
  •   glyvox    9 年前

    斯威夫特2

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

    斯威夫特3

    let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds
    
        7
  •  12
  •   Rajesh Loganathan Andrey    8 年前

    获取当前日期的毫秒数。

    斯威夫特4:

    func currentTimeInMilliSeconds()-> Int
        {
            let currentDate = Date()
            let since1970 = currentDate.timeIntervalSince1970
            return Int(since1970 * 1000)
        }
    
        8
  •  10
  •   Tyler    15 年前

    了解代码时间戳可能很有用,它提供了一个围绕基于马赫的定时函数的包装器。这使您获得纳秒级分辨率的定时数据——比毫秒高出1000000倍。是的,精确到一百万倍。(前缀是milli、micro、nano,每一个都比上一个精确1000倍。)即使您不需要代码时间戳,也可以查看代码(它是开源的)以了解它们如何使用mach获取计时数据。当您需要比nsdate方法更高的精度和更快的方法调用时,这将非常有用。

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

        9
  •  8
  •   Victor Sigler    11 年前
    // Timestamp after converting to milliseconds.
    
    NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];
    
        10
  •  7
  •   mmackh    13 年前

    我需要一个 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;
    

    结果应该和 [[nsdate]时间间隔从1970年开始]

        11
  •  4
  •   Inder Kumar Rathore user4622654    10 年前

    CFAbsoluteTimeGetCurrent()

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

        12
  •  4
  •   ΩlostA    10 年前

    试试这个:

    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来确保格式以前已经写入过。

        13
  •  4
  •   RenniePet    9 年前

    这与@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)
       }
    
        14
  •  2
  •   Softlabsindia    8 年前
     func currentmicrotimeTimeMillis() -> Int64{
    let nowDoublevaluseis = NSDate().timeIntervalSince1970
    return Int64(nowDoublevaluseis*1000)
    

    }

        15
  •  1
  •   DG7    10 年前

    这是我用来做斯威夫特的

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

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

        16
  •  0
  •   Chris    14 年前

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

        17
  •  0
  •   PANKAJ VERMA    8 年前
    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];
    
        18
  •  -2
  •   Duyhungws    11 年前

    使用此方法:

    [[NSDate date] timeIntervalSince1970]*1000;
    

    它喜欢 System.currentTimeMillis() 在爪哇;