新聞中心
當(dāng)我們寫完一個腳本或一個函數(shù),首先能保證得到正確結(jié)果,其次盡可能的快(雖然會說Py這玩意咋整都慢,但有的項目就是得要基于Py開發(fā))。

成都創(chuàng)新互聯(lián)公司專注于永川企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,商城網(wǎng)站建設(shè)。永川網(wǎng)站建設(shè)公司,為永川等地區(qū)提供建站服務(wù)。全流程定制網(wǎng)站開發(fā),專業(yè)設(shè)計,全程項目跟蹤,成都創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務(wù)
本期將總結(jié)幾種獲取程序運(yùn)行時間的方法,極大的幫助對比不同算法/寫法效率。
使用系統(tǒng)命令
每個操作系統(tǒng)都有自己的方法來算程序運(yùn)行的時間,比如在Windows PowerShell中,可以用 Measure-Command 來看一個Python文件的運(yùn)行時間:
Measure-Command {python tutorial.py}在Ubuntu中,使用time命令:
time python tutorial.py如果我們除了看整個 Python 腳本的運(yùn)行時間外還想看看局部運(yùn)行時間咋整?
使用 IPython 的 Magic Command
如果你使用過如Jupyter Notebook等工具會知道,他們用到了一個叫做 IPython 的交互式 Python 環(huán)境。
在 IPython 中,有一個特別方便的命令叫做 timeit。
對于某行代碼的測量可以使用%timeit:
對于某一個代碼單元格的測量,可以使用%%timeit:
使用timeit
如果不用IPython咋整,沒關(guān)系,已經(jīng)很厲害了,Python 有一個內(nèi)置的timeit模塊,可以幫助檢測小段代碼運(yùn)行時間。
可以在命令行界面運(yùn)行如下命令:
python -m timeit '[i for i in range(100)]'使用 timeit 測量執(zhí)行此列表推導(dǎo)式所需的時間,得到輸出:
200000 loops, best of 5: 1.4 usec per loop此輸出表明每次計時將執(zhí)行200000次列表推導(dǎo),共計時測試了5次,最好的結(jié)果是1.4毫秒。
或者直接在Python中調(diào)用:
import timeit
print(timeit.timeit('[i for i in range(100)]', number=1))對于更復(fù)雜的情況,有三個參數(shù)需要考慮:
- stmt:待測量的代碼片段,默認(rèn)是 pass
- setup:在運(yùn)行 stmt 之前執(zhí)行一些準(zhǔn)備工作,默認(rèn)也是 pass
- number:要運(yùn)行 stmt 的次數(shù)
比如一個更復(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模塊相信都不陌生,基本的用法是在待測代碼段的起始與末尾分別打上時間戳,然后獲得時間差:
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()來獲取時間,更精確,在之前的教程中有提過。
time模塊中還有一些其他計時選擇:
- time.timer():獲取當(dāng)前時間
- time.perf_counter():計算程序的執(zhí)行時間(高分辨率)
- time.monotonic():計算程序的執(zhí)行時間(低分辨率)
- time.process_time():計算某個進(jìn)程的CPU時間
- time.thread_time():計算線程的CPU時間
假如我們需要在多個代碼段測試運(yùn)行時間,每個首尾都打上時間戳再計算時間差就有點(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.如上例所示,這樣就使得代碼非常干凈與整潔。
網(wǎng)站名稱:你寫的Python代碼到底多快?這些測試工具了解了解
網(wǎng)頁地址:http://www.dlmjj.cn/article/dhcihcj.html


咨詢
建站咨詢
