如何獲得 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]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP