亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python 實現(xiàn)一個計時器

 更新時間:2020年07月28日 14:50:10   作者:David Beazley  
這篇文章主要介紹了Python 實現(xiàn)一個計時器的方法,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下

問題

你想記錄程序執(zhí)行多個任務所花費的時間

解決方案

time 模塊包含很多函數(shù)來執(zhí)行跟時間有關的函數(shù)。 盡管如此,通常我們會在此基礎之上構造一個更高級的接口來模擬一個計時器。例如:

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()

這個類定義了一個可以被用戶根據(jù)需要啟動、停止和重置的計時器。 它會在 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)

討論

本節(jié)提供了一個簡單而實用的類來實現(xiàn)時間記錄以及耗時計算。 同時也是對使用with語句以及上下文管理器協(xié)議的一個很好的演示。

在計時中要考慮一個底層的時間函數(shù)問題。一般來說, 使用 time.time() time.clock() 計算的時間精度因操作系統(tǒng)的不同會有所不同。 而使用 time.perf_counter() 函數(shù)可以確保使用系統(tǒng)上面最精確的計時器。

上述代碼中由 Timer 類記錄的時間是鐘表時間,并包含了所有休眠時間。 如果你只想計算該進程所花費的CPU時間,應該使用 time.process_time() 來代替:

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

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

以上就是Python 實現(xiàn)一個計時器的詳細內(nèi)容,更多關于Python 計時器的資料請關注腳本之家其它相關文章!

相關文章

最新評論