簡體   English   中英

iPhone:如何獲得當前毫秒?

[英]iPhone: How to get current milliseconds?

獲得當前系統時間毫秒的最佳方法是什么?

如果您正在考慮將其用於相對時間(例如游戲或動畫),我寧願使用CACurrentMediaTime()

double CurrentTime = CACurrentMediaTime();

這是推薦的方式; NSDate從網絡同步時鍾中獲取,並且在將其與網絡重新同步時偶爾會打嗝。

它返回當前的絕對時間,以秒為單位。


如果您想要小數部分(通常在同步動畫時使用),

let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)
[[NSDate date] timeIntervalSince1970];

它將自紀元以來的秒數作為雙精度返回。 我幾乎可以肯定你可以從小數部分訪問毫秒。

我在iPhone 4S和iPad 3(發布版本)上對所有其他答案進行了基准測試。 CACurrentMediaTime的開銷很小。 timeIntervalSince1970遠遠慢於其他,可能是由於NSDate實例化開銷,盡管它可能對許多用例無關緊要。

如果你想要最小的開銷並且不介意添加Quartz Framework依賴項,我建議使用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

在Swift中我們可以創建一個函數並執行如下操作

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

var currentTime = getCurrentMillis()

雖然它的做工精細的雨燕3.0,但我們可以通過修改和使用Date類代替NSDate3.0

Swift 3.0

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

var currentTime = getCurrentMillis()

到目前為止,我發現gettimeofday是iOS(iPad)上的一個很好的解決方案,當你想要執行一些間隔評估時(比如幀率,渲染幀的時間......):

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

斯威夫特2

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

斯威夫特3

let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds

獲取當前日期的毫秒數。

Swift 4+:

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

了解CodeTimestamps可能很有用,它提供了基於mach的定時函數的包裝器。 這為您提供納秒分辨率的定時數據 - 比毫秒更精確1000000倍。 是的,精確度要高出一百萬倍。 (前綴為milli,micro,nano,每個都比上一個精確1000倍。)即使您不需要CodeTimestamps,也請查看代碼(它是開源代碼),看看他們如何使用mach來獲取時序數據。 當您需要更高的精度並希望比NSDate方法更快的方法調用時,這將非常有用。

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

// Timestamp after converting to milliseconds.

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

我需要一個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]完全相同的結果

試試這個 :

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來確保格式化之前已經寫過。

CFAbsoluteTimeGetCurrent()

絕對時間以秒為單位,相對於2001年1月1日00:00:00 GMT的絕對參考日期。 正值表示參考日期之后的日期,負值表示之前的日期。 例如,絕對時間-32940326相當於1999年12月16日17:54:34。 重復調用此函數並不能保證單調增加結果。 由於與外部時間參考同步或由於時鍾的明確用戶改變,系統時間可能減少。

這與@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)
   }
 func currentmicrotimeTimeMillis() -> Int64{
let nowDoublevaluseis = NSDate().timeIntervalSince1970
return Int64(nowDoublevaluseis*1000)

}

這就是我用於Swift的東西

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

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

用這個網站來驗證准確性http://currentmillis.com/

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

如果您不想包含Quartz框架, [NSDate timeIntervalSinceReferenceDate]是另一個選項。 它返回一個double,表示秒。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM