dispatch_walltime與dispatch_time_t 的區別

dispatch_walltime的官方文檔解釋如下

Function

dispatch_walltime

// 根據系統時鐘,創建一個絕對時間
Creates a dispatch_time_t using an absolute time according to the wall clock.

Declaration

dispatch_time_t dispatch_walltime(const struct timespec *when, int64_t delta);
Parameters

when

// 一個時間結構體,如果傳入NULL,方法會默認使用當前時間
A struct timespec to add time to. If NULL is passed, then this function uses the result of gettimeofday.

delta

// 納秒
Nanoseconds to add.

Return Value

A new dispatch_time_t.

Discussion

// 基於gettimeofday的絕對時間
The wall clock is based on gettimeofday(:😃.

Time Constructs

  • dispatch_time
    Creates a dispatch_time_t relative to the default clock or modifies an existing dispatch_time_t.

  • dispatch_time_t
    An abstract representation of time.

  • DISPATCH_WALLTIME_NOW
    The current time.

我們可以看出dispatch_walltime生成的是根據系統時鐘的絕對時間,
第一個參數可以爲NULL,這樣默認爲當前時間
第二個參數的單位爲納秒
整個API的調用如下

// 當前時間1秒後的時間
dispatch_time_t time_t = dispatch_walltime(NULL, 1000 * 1000 * 1000);

我們再來看一下我們常見的dispatch_time_t的創建方式:

dispatch_time_t time_t2 = dispatch_time(DISPATCH_TIME_NOW, 1000 * 1000 * 1000);

表面上看沒有什麼不同,普通的使用也不會出現什麼區別.
但是dispatch_walltime的定義爲絕對時間,所謂絕對時間,就是不收到系統休眠等因素的影響,打比方說

我們使用dispatch_walltime創建一個time1,使用dispatch_time創建一個time2 ,兩個時間都是1個小時後的時間(12:15).我們用其創建兩個定時器,對應事件後出發一個事件.

  • 如果系統和程序正常運行,在不考慮runloop的情況下,兩個事件會如期同時出發.
  • 程序開始後,我們改變系統事件爲13:00,再進入程序,這時time1對應的事件會立即觸發.

也就是說,dispatch_time是相對的計數時鐘,而dispatch_walltime是絕對的系統時鐘

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章