問題描述
1、Python開發的程序在使用過程中很慢,想確定下是哪段代碼比較慢;
2、Python開發的程序在使用過程中占用內存很大,想確定下是哪段代碼引起的;
解決方案
使用profile分析分析cpu使用情況
可以使用profile和cProfile對python程序進行分析,這里主要記錄下cProfile的使用,profile參考cProfile即可。
#slots_test.py class Foobar(object): __slots__=('x') def __init__(self, x): self.x = x def main(): f = [Foobar(42) for i in range(1000000)] if __name__ == "__main__": main()
1.簡單查看
python -m cProfile slots_test.py
2.不修改程序
python -m cProfile -o test1.out slots_test.py
python -c "import pstats; p=pstats.Stats('test1.out'); p.print_stats()"
查看排序后的結果:
python -c "import pstats; p=pstats.Stats('test1.out'); p.sort_stats('time').print_stats()"
結果說明
ncalls : 函數的被調用次數 tottime :函數總計運行時間,除去函數中調用的函數運行時間 percall :函數運行一次的平均時間,等於tottime/ncalls cumtime :函數總計運行時間,含調用的函數運行時間 percall :函數運行一次的平均時間,等於cumtime/ncalls filename:lineno(function) 函數所在的文件名,函數的行號,函數名
使用memory_profiler分析內存使用情況
需要安裝memory_profiler :
pip install psutil pip install memory_profiler
1.不導入模塊
python -m memory_profiler slots_test.py
不加 -m memory_profiler會報錯
2.導入模塊
#slots_test.py from memory_profiler import profile class Foobar(object): __slots__=('x') def __init__(self, x): self.x = x @profile def main(): f = [Foobar(42) for i in range(1000000)] if __name__ == "__main__": main()
python slots_test.py