問題
你想記錄程序執行多個任務所花費的時間
解決方案
time 模塊包含很多函數來執行跟時間有關的函數。 盡管如此,通常我們會在此基礎之上構造一個更高級的接口來模擬一個計時器。例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import time class Timer: def __init__( self , func = time.perf_counter): self .elapsed = 0.0 self ._func = func self ._start = None def start( self ): if self ._start is not None : raise RuntimeError( 'Already started' ) self ._start = self ._func() def stop( self ): if self ._start is None : raise RuntimeError( 'Not started' ) end = self ._func() self .elapsed + = end - self ._start self ._start = None def reset( self ): self .elapsed = 0.0 @property def running( self ): return self ._start is not None def __enter__( self ): self .start() return self def __exit__( self , * args): self .stop() |
這個類定義了一個可以被用戶根據需要啟動、停止和重置的計時器。 它會在 elapsed
屬性中記錄整個消耗時間。 下面是一個例子來演示怎樣使用它:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
def countdown(n): while n > 0 : n - = 1 # Use 1: Explicit start/stop t = Timer() t.start() countdown( 1000000 ) t.stop() print (t.elapsed) # Use 2: As a context manager with t: countdown( 1000000 ) print (t.elapsed) with Timer() as t2: countdown( 1000000 ) print (t2.elapsed) |
討論
本節提供了一個簡單而實用的類來實現時間記錄以及耗時計算。 同時也是對使用with語句以及上下文管理器協議的一個很好的演示。
在計時中要考慮一個底層的時間函數問題。一般來說, 使用 time.time()
或 time.clock()
計算的時間精度因操作系統的不同會有所不同。 而使用 time.perf_counter()
函數可以確保使用系統上面最精確的計時器。
上述代碼中由 Timer
類記錄的時間是鐘表時間,并包含了所有休眠時間。 如果你只想計算該進程所花費的CPU時間,應該使用 time.process_time() 來代替:
1
2
3
4
|
t = Timer(time.process_time) with t: countdown( 1000000 ) print (t.elapsed) |
time.perf_counter()
和 time.process_time()
都會返回小數形式的秒數時間。 實際的時間值沒有任何意義,為了得到有意義的結果,你得執行兩次函數然后計算它們的差值。
以上就是Python 實現一個計時器的詳細內容,更多關于Python 計時器的資料請關注服務器之家其它相關文章!
原文鏈接:https://python3-cookbook.readthedocs.io/zh_CN/latest/c13/p13_making_stopwatch_timer.html