Python3標准庫:time時鍾時間


1. time時鍾時間

time模塊允許訪問多種類型的時鍾,分別用於不同的用途。標准系統調用(如time())會報告系統“牆上時鍾”時間。monotonic()時鍾可以用於測量一個長時間運行的進程的耗用時間(elapsed time),因為即使系統時間有改變,也能保證這個時鍾不會逆轉。對於性能測試,perf_counter()允許訪問有最高可用分辨率的時鍾,這使得短時間測量更為准確。CPU時間可以通過clock()得到,process_time()會返回處理器時間和系統時間的組合結果。

1.1 比較時鍾

時鍾的實現細節因平台而異。可以使用get_clock_info()獲得當前實現的基本信息,包括時鍾的分辨率。

import textwrap
import time

available_clocks = [
    ('monotonic', time.monotonic),
    ('perf_counter', time.perf_counter),
    ('process_time', time.process_time),
    ('time', time.time),
]

for clock_name, func in available_clocks:
    print(textwrap.dedent('''\
    {name}:
        adjustable    : {info.adjustable}
        implementation: {info.implementation}
        monotonic     : {info.monotonic}
        resolution    : {info.resolution}
        current       : {current}
    ''').format(
        name=clock_name,
        info=time.get_clock_info(clock_name),
        current=func())
    )

monotonic和perf_counter時鍾是通過相同的底層系統調用來實現的。

1.2 wall clock time 

time模塊的核心函數之一是time(),它會把從“紀元”開始以來的秒數作為一個浮點值返回。

import time

print('The time is:', time.time())

紀元是時間測量的起始點,對於UNIX系統這個起始時間就是1970年1月1日 0:00。盡管這個值總是一個浮點數,但具體的精度依賴於具體的平台。

浮點數表示對於存儲或比較日期很有用,但是對於生成人類刻度的表示就有些差強人意了。要記錄或打印時間,ctime()可能是更好的選擇。 

import time

print('The time is      :', time.ctime())
later = time.time() + 15
print('15 secs from now :', time.ctime(later))

這個例子中的第二個print()調用顯示了如何使用ctime()格式化非當前的時間的另一個時間值。

1.3 單調時鍾

由於time()查看系統時鍾,並且用戶或系統服務可能改變系統時鍾來同步多個計算機上的時鍾,所以反復調用time()所產生的值可能向前和向后。試圖測量持續時間或者使用這些時間來完成計算時,這可能會導致意想不到的行為。為了避免這些情況,可以使用monotonic(),它總是返回向前的值。

import time

start = time.monotonic()
time.sleep(0.1)
end = time.monotonic()
print('start : {:>9.2f}'.format(start))
print('end   : {:>9.2f}'.format(end))
print('span  : {:>9.2f}'.format(end - start))

單調時鍾的起始點沒有被定義,所以返回值只是在與其他時鍾值完成計算時有用。在這個例子中,使用monotonic()來測量睡眠持續時間。

1.4 處理器時鍾的時間

time()返回的是一個牆上時鍾時間,而clock()返回處理器時鍾時間。clock()返回的值反映了程序運行時使用的實際時間。

import hashlib
import time

# Data to use to calculate md5 checksums
data = open(__file__, 'rb').read()

for i in range(5):
    h = hashlib.sha1()
    print(time.ctime(), ': {:0.3f} {:0.3f}'.format(
        time.time(), time.process_time()))
    for i in range(300000):
        h.update(data)
    cksum = h.digest()

在這個例子中,每次循環迭代時,會打印格式化的ctime()時間,以及time()和clock()返回的浮點值。

一般情況下,如果程序什么也沒有做,則處理器時鍾不會“滴答”(tick)。

import time

template = '{} - {:0.2f} - {:0.2f}'

print(template.format(
    time.ctime(), time.time(), time.process_time())
)

for i in range(3, 0, -1):
    print('Sleeping', i)
    time.sleep(i)
    print(template.format(
        time.ctime(), time.time(), time.process_time())
    )

在這個例子中,循環幾乎不做什么工作,每次迭代后都會睡眠。應用睡眠時,time()值會增加,而clock()值不會增加。

調用sleep()會從事當前線程交出控制,並要求這個現場等待系統再次將其喚醒。如果程序只有一個線程,則這個函數實際上會阻塞應用,使它不做任何工作。 

1.5 性能計數器 

在測量性能時,高分辨率時鍾是必不可少的。要確定最好的時鍾數據源,需要有平台特定的知識,python通過perf_counter()來提供所需的這些知識。

import hashlib
import time

# Data to use to calculate md5 checksums
data = open(__file__, 'rb').read()

loop_start = time.perf_counter()

for i in range(5):
    iter_start = time.perf_counter()
    h = hashlib.sha1()
    for i in range(300000):
        h.update(data)
    cksum = h.digest()
    now = time.perf_counter()
    loop_elapsed = now - loop_start
    iter_elapsed = now - iter_start
    print(time.ctime(), ': {:0.3f} {:0.3f}'.format(
        iter_elapsed, loop_elapsed))

類似於monotonic(),perf_counter()的紀元未定義,所以返回值值用於比較和計算值,而不作為絕對時間。

1.6 時間組成

有些情況下需要把時間存儲為過去了多少秒(秒數),但是另外一些情況下,程序需要訪問一個日期的各個字段(例如,年和月)。time模塊定義了struct_time來保存日期和時間值,其中分解了各個組成部分以便於訪問。很多函數都要處理struct_time值不是浮點值。

import time

def show_struct(s):
    print('  tm_year :', s.tm_year)
    print('  tm_mon  :', s.tm_mon)
    print('  tm_mday :', s.tm_mday)
    print('  tm_hour :', s.tm_hour)
    print('  tm_min  :', s.tm_min)
    print('  tm_sec  :', s.tm_sec)
    print('  tm_wday :', s.tm_wday)
    print('  tm_yday :', s.tm_yday)
    print('  tm_isdst:', s.tm_isdst)

print('gmtime:')
show_struct(time.gmtime())
print('\nlocaltime:')
show_struct(time.localtime())
print('\nmktime:', time.mktime(time.localtime()))

gmtime()函數以UTC格式返回當前時間。localtime()會返回應用了當前時區的當前時間。mktime()取一個struct_time實例,將它轉換為浮點數表示。

1.7 解析和格式化時間

函數strptime()和strftime()可以在時間值的struct_time表示和字符串表示之間轉換。這兩個函數支持大量格式化指令,允許不同方式的輸入和輸出。

下面的這個例子將當前時間從字符串轉換為struct_time實例,然后再轉換回字符串。

import time

def show_struct(s):
    print('  tm_year :', s.tm_year)
    print('  tm_mon  :', s.tm_mon)
    print('  tm_mday :', s.tm_mday)
    print('  tm_hour :', s.tm_hour)
    print('  tm_min  :', s.tm_min)
    print('  tm_sec  :', s.tm_sec)
    print('  tm_wday :', s.tm_wday)
    print('  tm_yday :', s.tm_yday)
    print('  tm_isdst:', s.tm_isdst)

now = time.ctime(1483391847.433716)
print('Now:', now)

parsed = time.strptime(now)
print('\nParsed:')
show_struct(parsed)

print('\nFormatted:',
      time.strftime("%a %b %d %H:%M:%S %Y", parsed))

輸出字符串與輸入字符串並不完全相同,因為日期前面加了一個前綴0(由“2”變為"02")。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM