你寫的Python代碼到底多快?這些測試工具了解了解
當(dāng)我們寫完一個(gè)腳本或一個(gè)函數(shù),首先能保證得到正確結(jié)果,其次盡可能的快(雖然會(huì)說Py這玩意咋整都慢,但有的項(xiàng)目就是得要基于Py開發(fā))。
本期將總結(jié)幾種獲取程序運(yùn)行時(shí)間的方法,極大的幫助對(duì)比不同算法/寫法效率。
使用系統(tǒng)命令
每個(gè)操作系統(tǒng)都有自己的方法來算程序運(yùn)行的時(shí)間,比如在Windows PowerShell中,可以用 Measure-Command 來看一個(gè)Python文件的運(yùn)行時(shí)間:
Measure-Command {python tutorial.py}
在Ubuntu中,使用time命令:
time python tutorial.py
如果我們除了看整個(gè) Python 腳本的運(yùn)行時(shí)間外還想看看局部運(yùn)行時(shí)間咋整?
使用 IPython 的 Magic Command
如果你使用過如Jupyter Notebook等工具會(huì)知道,他們用到了一個(gè)叫做 IPython 的交互式 Python 環(huán)境。
在 IPython 中,有一個(gè)特別方便的命令叫做 timeit。
對(duì)于某行代碼的測量可以使用%timeit:
對(duì)于某一個(gè)代碼單元格的測量,可以使用%%timeit:
使用timeit
如果不用IPython咋整,沒關(guān)系,已經(jīng)很厲害了,Python 有一個(gè)內(nèi)置的timeit模塊,可以幫助檢測小段代碼運(yùn)行時(shí)間。
可以在命令行界面運(yùn)行如下命令:
python -m timeit '[i for i in range(100)]'
使用 timeit 測量執(zhí)行此列表推導(dǎo)式所需的時(shí)間,得到輸出:
200000 loops, best of 5: 1.4 usec per loop
此輸出表明每次計(jì)時(shí)將執(zhí)行200000次列表推導(dǎo),共計(jì)時(shí)測試了5次,最好的結(jié)果是1.4毫秒。
或者直接在Python中調(diào)用:
import timeit
print(timeit.timeit('[i for i in range(100)]', number=1))
對(duì)于更復(fù)雜的情況,有三個(gè)參數(shù)需要考慮:
- stmt:待測量的代碼片段,默認(rèn)是 pass
- setup:在運(yùn)行 stmt 之前執(zhí)行一些準(zhǔn)備工作,默認(rèn)也是 pass
- number:要運(yùn)行 stmt 的次數(shù)
比如一個(gè)更復(fù)雜的例子:
import timeit
# prerequisites before running the stmt
my_setup = "from math import sqrt"
# code snippet we would like to measure
my_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
使用time模塊
Python中內(nèi)置的time模塊相信都不陌生,基本的用法是在待測代碼段的起始與末尾分別打上時(shí)間戳,然后獲得時(shí)間差:
import time
def my_function():
for i in range(10000000):
pass
start = time.perf_counter()
my_function()
print(time.perf_counter()-start)
# 0.1179838
我經(jīng)常使用time.perf_counter()來獲取時(shí)間,更精確,在之前的教程中有提過。
time模塊中還有一些其他計(jì)時(shí)選擇:
- time.timer():獲取當(dāng)前時(shí)間
- time.perf_counter():計(jì)算程序的執(zhí)行時(shí)間(高分辨率)
- time.monotonic():計(jì)算程序的執(zhí)行時(shí)間(低分辨率)
- time.process_time():計(jì)算某個(gè)進(jìn)程的CPU時(shí)間
- time.thread_time():計(jì)算線程的CPU時(shí)間
假如我們需要在多個(gè)代碼段測試運(yùn)行時(shí)間,每個(gè)首尾都打上時(shí)間戳再計(jì)算時(shí)間差就有點(diǎn)繁瑣了,咋整,上裝飾器:
import time
def 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_time
def my_function():
for i in range(10000000):
pass
my_function()
# The execution of my_function used 0.1156899 seconds.
如上例所示,這樣就使得代碼非常干凈與整潔。