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

iPhone: How to get current milliseconds?

提问人: 提问时间:12/11/2008 最后编辑:TheNeil 更新时间:9/3/2019 访问量:277329

问:

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

iOS iPhone 当前时间

评论


答:

288赞 codelogic 12/11/2008 #1
[[NSDate date] timeIntervalSince1970];

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

评论

5赞 Ege Akpinar 6/30/2014
我已经使用这种方法一段时间了,并且意识到当您在几毫秒后调用它时,它可以返回更早的值(例如,连续调用它,您可能不会最终得到递增的序列)
5赞 Hot Licks 9/13/2014
[NSDate timeIntervalSinceReferenceDate]更便宜。(尽管它引用了不同的“纪元”——如果你想要 1970 年,请添加常量。NSTimeIntervalSince1970
1赞 Kris Subramanian 4/18/2015
timeIntervalSince1970 是 NSDate 上的实例属性,而不是静态方法。因此,仍然必须编写 NSTimeInterval myInterval = [NSDate date].timeIntervalSince1970 !!
1赞 Mihir Oza 10/16/2015
以毫秒为单位 CurrentTime = [[NSDate date] timeIntervalSince1970] * 1000;
2赞 Incinerator 12/14/2017
@Satyam实际上乘以 1000 会得到毫秒精度,但根据文档,返回的 TimeInterval 实际上是具有“亚毫秒精度”的 Double。timeIntervalSince1970
330赞 Allan Simonsen 4/30/2010 #2

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

double CurrentTime = CACurrentMediaTime();

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

它返回当前绝对时间(以秒为单位)。


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

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

评论

8赞 Kay 6/30/2011
但似乎花费了 [[NSDate date] timeIntervalSince1970 所需时间的两倍。我在 0.065 次通话中测量了 0.033 毫秒和 15000 毫秒。
9赞 BadPirate 2/22/2012
哎呀 - 那是导入 #import < QuartzCore/CAAnimation.h>
6赞 Gabe Johnson 9/19/2012
对于那些刚接触 Xcode(像我一样)的人来说,“包含 Quartz 框架”意味着将其添加到“将二进制文件与库链接”中的库集中。
3赞 Anthony Mattox 2/14/2014
如果有人在寻找与 SpriteKit 相关的内容,那么 SKScene 的更新方法中的“当前时间”确实是 CACurrentMediaTime();
3赞 Pavel Alexeev 6/21/2018
重要提示:CACurrentMediaTime() 在设备处于睡眠状态时不滴答!
0赞 Chris 4/5/2011 #3

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

10赞 Tyler 6/28/2011 #4

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

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

评论

0赞 Dan Rosenstark 10/7/2011
如果您使用的是 ARC :),您可能需要一个-fno-objc-arc
1赞 Tomas Andrle 7/23/2014
镜像: web.archive.org/web/20131030113838/http://eng.pulse.me/...
3赞 Tomas Andrle 7/23/2014
从页面链接的源代码在这里:github.com/tylerneylon/moriarty
31赞 Tristan Lorach 10/25/2011 #5

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

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

评论

2赞 AbePralle 12/2/2011
我也喜欢这个,因为它非常便携。请注意,根据操作系统的不同,您可能需要使用“long long”而不是“long”,同样,在执行其余计算之前,将time.tv_sec转换为“long long”。
0赞 David H 4/26/2012
静态无符号长 getMStime(void) { struct timeval time; gettimeofday(&time, NULL); return (time.tv_sec * 1000) + (time.tv_usec / 1000); }
0赞 Hyndrix 2/19/2014
有趣的是,这在我的 iPhone 5S 和 Mac 上运行良好,但在 iPad 3 上返回错误值。
0赞 jason gilbert 1/18/2015
为了避免得到负数,我不得不在数学之前进行投票:int64_t结果 = ((int64_t)tv.tv_sec * 1000) + ((int64_t)tv.tv_usec / 1000);
0赞 Muhammad Shauket 5/13/2016
它以 -ve 为单位返回时间
100赞 darrinm 8/19/2012 #6

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

如果您想要最小的开销并且不介意添加 Quartz Framework 依赖项,我建议您这样做。或者,如果便携性是您的首要任务。CACurrentMediaTimegettimeofday

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赞 Steven Lu 4/7/2014
+1,虽然这显然是非常有用和有帮助的,但如果没有看到一些源代码;),我不会完全称其为伟大的工程工作
3赞 mojuba 7/25/2015
但要注意这个问题:bendodson.com/weblog/2013/01/29/ca-current-media-time 当设备进入睡眠状态时,这个时钟显然会停止。
1赞 Ozgur Vatansever 11/11/2016
有最快的宏。NSTimeIntervalSince1970
1赞 YourMJK 3/3/2020
@ozgur 是一个常数,用于描述 1970-01-01 和“参考日期”(即 2001-01-01)之间的秒数,因此它始终等于 978307200NSTimeIntervalSince1970
6赞 mmackh 5/11/2013 #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;

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

8赞 Fatima Arshad 9/24/2014 #8
// Timestamp after converting to milliseconds.

NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];
57赞 Rajan Maheshwari 10/3/2015 #9

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

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

var currentTime = getCurrentMillis()

虽然它在 Swift 3.0 中工作正常,但我们可以修改和使用该类而不是在 3.0DateNSDate

斯威夫特 3.0

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

var currentTime = getCurrentMillis()
4赞 ΩlostA 12/2/2015 #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 来确保格式之前已经写过。

5赞 Inder Kumar Rathore 12/31/2015 #11

CFAbsoluteTimeGetCurrent()

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

1赞 DG7 1/14/2016 #12

这就是我用于 Swift 的方法

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

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

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

18赞 quemeful 1/18/2016 #13

斯威夫特 2

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

斯威夫特 3

let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds

评论

4赞 Leo Dabus 2/7/2019
TimeIntervalaka 没有毫秒属性。DoubleDate().timeIntervalSince1970 * 1000
5赞 RenniePet 12/28/2016 #14

这与 @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)
   }
1赞 PANKAJ VERMA 1/11/2018 #15
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];
2赞 Softlabsindia 4/7/2018 #16
 func currentmicrotimeTimeMillis() -> Int64{
let nowDoublevaluseis = NSDate().timeIntervalSince1970
return Int64(nowDoublevaluseis*1000)

}

33赞 Rajesh Loganathan 7/10/2018 #17

获取当前日期的毫秒数。

斯威夫特 4+:

func currentTimeInMilliSeconds()-> Int
    {
        let currentDate = Date()
        let since1970 = currentDate.timeIntervalSince1970
        return Int(since1970 * 1000)
    }
3赞 lazyTank 4/25/2019 #18
let timeInMiliSecDate = Date()
let timeInMiliSec = Int (timeInMiliSecDate.timeIntervalSince1970 * 1000)
print(timeInMiliSec)

评论

0赞 Nico Haase 4/25/2019
请在您的代码中添加一些解释,以便其他人可以从中学习 - 特别是如果您发布的问题的答案已经有很多赞成的答案