如何獲取 Python 程式碼的執行速度時序?


要測量程式執行時間,可以使用 time.clock() 或 time.time() 函式。Python 文件指出,該函式應用於基準測試目的。 

示例

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

輸出

輸出如下 −

Time elapsed:  0.0009403145040156798

您還可以使用 timeit 模組來獲取程式碼片段執行時間的適當統計分析。它多次執行該片段,然後報告最短執行時間。您可以按如下方式使用它

示例

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]


更新日期: 2020-02-19

2K+ 瀏覽

啟動你的 職業

透過完成課程獲得認證

開始
廣告