python标准库time_Python3标准库:time时钟时间
1. time時鐘時間
time模塊允許訪問多種類型的時鐘,分別用于不同的用途。標準系統調用(如time())會報告系統“墻上時鐘”時間。monotonic()時鐘可以用于測量一個長時間運行的進程的耗用時間(elapsed time),因為即使系統時間有改變,也能保證這個時鐘不會逆轉。對于性能測試,perf_counter()允許訪問有最高可用分辨率的時鐘,這使得短時間測量更為準確。CPU時間可以通過clock()得到,process_time()會返回處理器時間和系統時間的組合結果。
1.1 比較時鐘
時鐘的實現細節因平臺而異。可以使用get_clock_info()獲得當前實現的基本信息,包括時鐘的分辨率。
importtextwrapimporttime
available_clocks=[
('monotonic', time.monotonic),
('perf_counter', time.perf_counter),
('process_time', time.process_time),
('time', time.time),
]for clock_name, func inavailable_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(),它會把從“紀元”開始以來的秒數作為一個浮點值返回。
importtimeprint('The time is:', time.time())
紀元是時間測量的起始點,對于UNIX系統這個起始時間就是1970年1月1日 0:00。盡管這個值總是一個浮點數,但具體的精度依賴于具體的平臺。
浮點數表示對于存儲或比較日期很有用,但是對于生成人類刻度的表示就有些差強人意了。要記錄或打印時間,ctime()可能是更好的選擇。
importtimeprint('The time is :', time.ctime())
later= time.time() + 15
print('15 secs from now :', time.ctime(later))
這個例子中的第二個print()調用顯示了如何使用ctime()格式化非當前的時間的另一個時間值。
1.3 單調時鐘
由于time()查看系統時鐘,并且用戶或系統服務可能改變系統時鐘來同步多個計算機上的時鐘,所以反復調用time()所產生的值可能向前和向后。試圖測量持續時間或者使用這些時間來完成計算時,這可能會導致意想不到的行為。為了避免這些情況,可以使用monotonic(),它總是返回向前的值。
importtime
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()返回的值反映了程序運行時使用的實際時間。
importhashlibimporttime#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)。
importtime
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()來提供所需的這些知識。
importhashlibimporttime#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_startprint(time.ctime(), ': {:0.3f} {:0.3f}'.format(
iter_elapsed, loop_elapsed))
類似于monotonic(),perf_counter()的紀元未定義,所以返回值值用于比較和計算值,而不作為絕對時間。
1.6 時間組成
有些情況下需要把時間存儲為過去了多少秒(秒數),但是另外一些情況下,程序需要訪問一個日期的各個字段(例如,年和月)。time模塊定義了struct_time來保存日期和時間值,其中分解了各個組成部分以便于訪問。很多函數都要處理struct_time值不是浮點值。
importtimedefshow_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實例,然后再轉換回字符串。
importtimedefshow_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")。
總結
以上是生活随笔為你收集整理的python标准库time_Python3标准库:time时钟时间的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中定义的函数不掉用不会执行_
- 下一篇: websocket python爬虫_p