1. 程式人生 > 程式設計 >Python 實現一個計時器

Python 實現一個計時器

問題

你想記錄程式執行多個任務所花費的時間

解決方案

time 模組包含很多函式來執行跟時間有關的函式。 儘管如此,通常我們會在此基礎之上構造一個更高階的介面來模擬一個計時器。例如:

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 屬性中記錄整個消耗時間。 下面是一個例子來演示怎樣使用它:

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() 來代替:

t = Timer(time.process_time)
with t:
  countdown(1000000)
print(t.elapsed)

time.perf_counter() time.process_time() 都會返回小數形式的秒數時間。 實際的時間值沒有任何意義,為了得到有意義的結果,你得執行兩次函式然後計算它們的差值。

以上就是Python 實現一個計時器的詳細內容,更多關於Python 計時器的資料請關注我們其它相關文章!