如何在 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

2000+ 次瀏覽

開啟您的 職業生涯

完成課程後獲得認證

馬上開始
廣告
© . All rights reserved.