Python 實(shí)現(xiàn)一個(gè)計(jì)時(shí)器
問題
你想記錄程序執(zhí)行多個(gè)任務(wù)所花費(fèi)的時(shí)間
解決方案
time 模塊包含很多函數(shù)來執(zhí)行跟時(shí)間有關(guān)的函數(shù)。 盡管如此,通常我們會(huì)在此基礎(chǔ)之上構(gòu)造一個(gè)更高級(jí)的接口來模擬一個(gè)計(jì)時(shí)器。例如:
import timeclass 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()
這個(gè)類定義了一個(gè)可以被用戶根據(jù)需要啟動(dòng)、停止和重置的計(jì)時(shí)器。 它會(huì)在 elapsed 屬性中記錄整個(gè)消耗時(shí)間。 下面是一個(gè)例子來演示怎樣使用它:
def countdown(n): while n > 0: n -= 1# Use 1: Explicit start/stopt = Timer()t.start()countdown(1000000)t.stop()print(t.elapsed)# Use 2: As a context managerwith t: countdown(1000000)print(t.elapsed)with Timer() as t2: countdown(1000000)print(t2.elapsed)
討論
本節(jié)提供了一個(gè)簡(jiǎn)單而實(shí)用的類來實(shí)現(xiàn)時(shí)間記錄以及耗時(shí)計(jì)算。 同時(shí)也是對(duì)使用with語句以及上下文管理器協(xié)議的一個(gè)很好的演示。
在計(jì)時(shí)中要考慮一個(gè)底層的時(shí)間函數(shù)問題。一般來說, 使用 time.time() 或 time.clock() 計(jì)算的時(shí)間精度因操作系統(tǒng)的不同會(huì)有所不同。 而使用 time.perf_counter() 函數(shù)可以確保使用系統(tǒng)上面最精確的計(jì)時(shí)器。
上述代碼中由 Timer 類記錄的時(shí)間是鐘表時(shí)間,并包含了所有休眠時(shí)間。 如果你只想計(jì)算該進(jìn)程所花費(fèi)的CPU時(shí)間,應(yīng)該使用 time.process_time() 來代替:
t = Timer(time.process_time)with t: countdown(1000000)print(t.elapsed)
time.perf_counter() 和 time.process_time() 都會(huì)返回小數(shù)形式的秒數(shù)時(shí)間。 實(shí)際的時(shí)間值沒有任何意義,為了得到有意義的結(jié)果,你得執(zhí)行兩次函數(shù)然后計(jì)算它們的差值。
以上就是Python 實(shí)現(xiàn)一個(gè)計(jì)時(shí)器的詳細(xì)內(nèi)容,更多關(guān)于Python 計(jì)時(shí)器的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis2. Python 忽略文件名編碼的方法3. python 基于Appium控制多設(shè)備并行執(zhí)行4. android studio實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器(無bug)5. Java Media Framework 基礎(chǔ)教程6. 解決vue頁(yè)面刷新,數(shù)據(jù)丟失的問題7. python 實(shí)現(xiàn)圍棋游戲(純tkinter gui)8. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作9. 在Mac中配置Python虛擬環(huán)境過程解析10. Python趣味挑戰(zhàn)之用pygame實(shí)現(xiàn)簡(jiǎn)單的金幣旋轉(zhuǎn)效果
