當我們寫完一個腳本或一個函數,首先能保證得到正確結果,其次盡可能的快(雖然會說Py這玩意咋整都慢,但有的項目就是得要基于Py開發)。
本期將總結幾種獲取程序運行時間的方法,極大的幫助對比不同算法/寫法效率。
每個操作系統都有自己的方法來算程序運行的時間,比如在Windows PowerShell中,可以用 Measure-Command 來看一個Python文件的運行時間:
Measure-Command {python tutorial.py}
在Ubuntu中,使用time命令:
time python tutorial.py
如果我們除了看整個 Python 腳本的運行時間外還想看看局部運行時間咋整
如果你使用過如Jupyter Notebook等工具會知道,他們用到了一個叫做 IPython 的交互式 Python 環境。
在 IPython 中,有一個特別方便的命令叫做 timeit。
對于某行代碼的測量可以使用%timeit:
對于某一個代碼單元格的測量,可以使用%%timeit:
如果不用IPython咋整,沒關系,已經很厲害了,Python 有一個內置的timeit模塊,可以幫助檢測小段代碼運行時間
可以在命令行界面運行如下命令:
python -m timeit '[i for i in range(100)]'
使用 timeit 測量執行此列表推導式所需的時間,得到輸出:
200000 loops, best of 5: 1.4 usec per loop
此輸出表明每次計時將執行200000次列表推導,共計時測試了5次,最好的結果是1.4毫秒。
或者直接在Python中調用:
import timeitprint(timeit.timeit('[i for i in range(100)]', number=1))
對于更復雜的情況,有三個參數需要考慮:
比如一個更復雜的例子:
import timeit# prerequisites before running the stmtmy_setup = "from math import sqrt"# code snippet we would like to measuremy_code = '''def my_function(): for x in range(10000000): sqrt(x)'''print(timeit.timeit(setup=my_setup, stmt=my_code, number=1000))# 6.260000000000293e-05
Python中內置的time模塊相信都不陌生,基本的用法是在待測代碼段的起始與末尾分別打上時間戳,然后獲得時間差:
import timedef my_function(): for i in range(10000000): passstart = time.perf_counter()my_function()print(time.perf_counter()-start)# 0.1179838
我經常使用time.perf_counter()來獲取時間,更精確,在之前的教程中有提過。
time模塊中還有一些其他計時選擇:
假如我們需要在多個代碼段測試運行時間,每個首尾都打上時間戳再計算時間差就有點繁瑣了,咋整,上裝飾器:
import timedef log_execution_time(func): def wrapper(*args, **kwargs): start = time.perf_counter() res = func(*args, **kwargs) end = time.perf_counter() print(f'The execution of {func.__name__} used {end - start} seconds.') return res return wrapper@log_execution_timedef my_function(): for i in range(10000000): passmy_function()# The execution of my_function used 0.1156899 seconds.
如上例所示,這樣就使得代碼肥腸干凈與整潔。
本文鏈接:http://www.tebozhan.com/showinfo-26-16609-0.html你寫的Python代碼到底多快?這些測試工具了解了解
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: React性能優化之useMemo、useCallback
下一篇: 增強現實可穿戴設備如何提高醫療保健效率