python性能測量工具cProfile使用解析
背景:
Python是一種解釋性的語言,執(zhí)行速度相比C、C++等語言十分緩慢;因此我們需要在其它地方上下功夫來提高代碼的執(zhí)行速度。
首先需要對代碼進行分析,這個時候則需要用一些工具。
這里介紹cProfile:
全代碼分析:
命令行:
cProfile -s tottime your_program.py
結(jié)果如下:
ncalls tottime percall cumtime percall filename:lineno(function)
66 0.001 0.000 11.850 0.180 base.py:228(micro_service)
66 0.003 0.000 11.849 0.180 tools.py:557(micro_service)
1056 0.001 0.000 11.073 0.010 connection.py:463(drain_events)
1056 0.015 0.000 11.072 0.010 connection.py:466(blocking_read)
1056 0.008 0.000 10.920 0.010 transport.py:233(read_frame)
3168 0.014 0.000 10.908 0.003 transport.py:370(_read)
3168 10.892 0.003 10.892 0.003 {method 'recv' of '_socket.socket' objects}
66 0.001 0.000 9.814 0.149 rpc.py:350(__call__)
66 0.001 0.000 8.395 0.127 rpc.py:329(result)
塊分析:
上面屬于文件分析,但是我們可能只對部分代碼感興趣,那么只需要在這部分代碼的前后加上下面這兩段代碼即可:
import cProfile cp = cProfile.Profile() cp.enable() YOUR CODE cp.disable() cp.print_stats()
結(jié)果與全代碼分析的類似,但是只包含你感興趣的部分。
行分析:
行分析需要安裝line_profiler:
pip install line_profiler
@profile def class_name() pass
然后在命令行輸入:
kernprof -l -v your_code.py -l 逐行分析 -v 立即查看結(jié)果
示例:
from cProfile import Profile as profile
from pstats import Stats
def ():
p = profile()
p.snapshot_stats()
p.enable()
p.disable()
p.print_stats(2) # 按照調(diào)用累加總耗時累加排序,即將最耗時的函數(shù)最優(yōu)先
p.dump_stats("call.log")
關(guān)于profile和cProfile的更多鏈接,請點擊:
https://docs.python.org/3/library/profile.html?spm=5176.100239.0.0.qa5fU5
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python實現(xiàn)簡易的學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細介紹了python實現(xiàn)簡易的學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05
解決python matplotlib imshow無法顯示的問題
今天小編就為大家分享一篇解決python matplotlib imshow無法顯示的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
python scipy.misc.imsave()函數(shù)的用法說明
這篇文章主要介紹了python scipy.misc.imsave()函數(shù)的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05

