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


[[NSDate date] timeIntervalSince1970];

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


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

double CurrentTime = CACurrentMediaTime();

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

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


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

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

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


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/


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

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

我在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

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


// Timestamp after converting to milliseconds.

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

在Swift中,我们可以创建一个函数,并如下所示

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

var currentTime = getCurrentMillis()

虽然它在Swift 3.0中工作得很好,但我们可以修改和使用Date类而不是3.0中的NSDate

斯威夫特3.0

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

var currentTime = getCurrentMillis()

试试这个:

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结合使用。它将返回带有年、月、日的日期和带有小时、分钟、秒和毫秒的时间。参见示例:"2015-12-02 04:43:15.008"。我使用NSString来确保格式之前已经写过。


CFAbsoluteTimeGetCurrent ()

Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT. A positive value represents a date after the reference date, a negative value represents a date before it. For example, the absolute time -32940326 is equivalent to December 16th, 1999 at 17:54:34. Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.


这是我给斯威夫特用的

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

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

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


斯威夫特2

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

斯威夫特3

let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds

这基本上和@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)
   }

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];

 func currentmicrotimeTimeMillis() -> Int64{
let nowDoublevaluseis = NSDate().timeIntervalSince1970
return Int64(nowDoublevaluseis*1000)

}


获取当前日期的毫秒数。

斯威夫特4 +:

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

let timeInMiliSecDate = Date()
let timeInMiliSec = Int (timeInMiliSecDate.timeIntervalSince1970 * 1000)
print(timeInMiliSec)