1 回答
TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
從命令行,將timeit模塊作為傳遞附加設(shè)置參數(shù) (-s)的腳本運(yùn)行。設(shè)置應(yīng)該從腳本中導(dǎo)入您想要計(jì)時(shí)的函數(shù)。
最后,記住添加對(duì)該函數(shù)的調(diào)用。
警告:安裝程序?qū)⑦\(yùn)行一次,導(dǎo)入您的腳本。導(dǎo)入運(yùn)行所有“不受保護(hù)的代碼”,因此請(qǐng)記住使用if __name__ == "__main__"約定將函數(shù)/對(duì)象聲明與實(shí)際執(zhí)行分開(kāi)。
想象一下以下 script.py
import time
print('This will be run on import')
def fun():
pass
def very_complex_function_that_takes_an_hour_to_run():
time.sleep(3600)
if __name__ == '__main__':
print("Nothing beyond the if condition will be run on import")
very_complex_function_that_takes_an_hour_to_run()
讓我們計(jì)時(shí)fun,運(yùn)行 100 次。
$ python -m timeit -s 'from test import fun' -n 100 'fun()'
輸出
This will be run on import
100 loops, best of 5: 66.6 nsec per loop
添加回答
舉報(bào)
