Python 中計(jì)算程序運(yùn)行時(shí)間常用方法

轉(zhuǎn)載鏈接: https://mp.weixin.qq.com/s/ml7W3GVeG84gQ8i2TguOuQ

(1) 測(cè)試代碼運(yùn)行時(shí)間

import time
tic = time.time()
much_job = [x**2 for x in range(1, 10**6, 3)]
toc = time.time()
print(f"used {toc-tic} s")

(2) 測(cè)試代碼多次運(yùn)行的平均時(shí)間

from timeit import timeit
g = lambda x: x**2+1


def main():
    return(g(2)**120)

# 計(jì)算 10 次運(yùn)行的平均時(shí)間
ret = timeit("main()", globals={"main":main}, number=10)
print(ret)

(3) 按照調(diào)用函數(shù)分析代碼運(yùn)行的時(shí)間

import profile

def relu(x):
    return(x if x>0 else 0)


def main():
    res = [relu(x) for x in range(-100000, 100000, 1)]
    return res

profile.run("main()")

(4) 按行分析代碼運(yùn)行時(shí)間

# 安裝: pip install --upgrade pip; pip install line_profile
# 或者嘗試 sudo pip install --pre line_profiler 或 sudo pip install line_profiler==1.0b3
# 或者嘗試使用科學(xué)計(jì)算環(huán)境

from line_profile import LineProfile

def relu(x):
    return(x if x>0 else 0)


def main():
    res = [relu(x) for x in range(-100000, 100000, 1)]
    return res

lprofile = LineProfile(main, relu)
lprofile.run("main()")
lprofile.print_status()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容