如何在 python 中測量已過去的時間?


要測量程式執行期間的已過去時間,可以使用 time.clock() 或 time.time() 函式。python 文件指出,此函式應用於基準測試。 

示例

import time
t0= time.clock()
print("Hello")
t1 = time.clock() - t0
print("Time elapsed: ", t1) # CPU seconds elapsed (floating point)

輸出

這將產生以下輸出 −

Time elapsed:  1.2999999999999123e-05

你還可以使用 time 模組根據程式碼段的執行時間獲取適當的統計分析。 它會多次執行程式碼段,然後告訴你最短執行時間。你可以按照以下方法使用它

示例

def f(x):

  return x * x

import timeit

timeit.repeat("for x in range(100): f(x)", "from __main__ import f", number=100000)

輸出

這將產生以下輸出 −

[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]

更新日期:07-06-2020

2K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得證書

開始
廣告