python profile_python程序之profile分析
操作系統(tǒng) : CentOS7.3.1611_x64
python版本:2.7.5
問題描述
1、Python開發(fā)的程序在使用過程中很慢,想確定下是哪段代碼比較慢;
2、Python開發(fā)的程序在使用過程中占用內(nèi)存很大,想確定下是哪段代碼引起的;
解決方案
使用profile分析分析cpu使用情況
可以使用profile和cProfile對(duì)python程序進(jìn)行分析,這里主要記錄下cProfile的使用,profile參考cProfile即可。
假設(shè)有如下代碼需要進(jìn)行分析(cProfileTest1.py):
#! /usr/bin/env python#-*- coding:utf-8 -*-
deffoo():
sum=0for i in range(100):
sum+=ireturnsumif __name__ == "__main__":
foo()
可以通過以下兩種使用方式進(jìn)行分析:
1、不修改程序
分析程序:
python -m cProfile -o test1.out cProfileTest1.py
查看運(yùn)行結(jié)果:
python -c "import pstats; p=pstats.Stats('test1.out'); p.print_stats()"
查看排序后的運(yùn)行結(jié)果:
python -c "import pstats; p=pstats.Stats('test1.out'); p.sort_stats('time').print_stats()"
2、修改程序
加入如下代碼:
importcProfile
cProfile.run("foo()")
運(yùn)行效果如下:
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)1 0.000 0.000 0.000 0.000 :1()1 0.000 0.000 0.000 0.000 cProfileTest2.py:4(foo)1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler'objects}1 0.000 0.000 0.000 0.000 {range}
結(jié)果說明:
ncalls : 函數(shù)的被調(diào)用次數(shù)
tottime :函數(shù)總計(jì)運(yùn)行時(shí)間,除去函數(shù)中調(diào)用的函數(shù)運(yùn)行時(shí)間
percall :函數(shù)運(yùn)行一次的平均時(shí)間,等于tottime/ncalls
cumtime :函數(shù)總計(jì)運(yùn)行時(shí)間,含調(diào)用的函數(shù)運(yùn)行時(shí)間
percall :函數(shù)運(yùn)行一次的平均時(shí)間,等于cumtime/ncalls
filename:lineno(function) 函數(shù)所在的文件名,函數(shù)的行號(hào),函數(shù)名
使用memory_profiler分析內(nèi)存使用情況
需要安裝memory_profiler :
pip installpsutil
pipinstall memory_profiler
假設(shè)有如下代碼需要進(jìn)行分析:
def my_func():
a= [1] * (10*6)
b= [2] * (10*7)
del b
return a
使用memory_profiler是需要修改代碼的,這里記錄下以下兩種使用方式:
1、不導(dǎo)入模塊使用
@profile
def my_func():
a= [1] * (10*6)
b= [2] * (10*7)
del b
return a
profile分析:
python -m memory_profiler test1.py
2、導(dǎo)入模塊使用
from memory_profiler import profile
@profile
def my_func():
a= [1] * (10*6)
b= [2] * (10*7)
del b
return a
完整代碼如下:
直接運(yùn)行程序即可進(jìn)行分析。
運(yùn)行效果如下:
(py27env) [mike@local test]$ python test1.py
Filename: test1.py
Line # Mem usage Increment Line Contents================================================
6 29.5 MiB 0.0MiB @profile7def my_func():8 29.5 MiB 0.0 MiB a = [1] * (10*6)9 29.5 MiB 0.0 MiB b = [2] * (10*7)10 29.5 MiB 0.0MiB del b11 29.5 MiB 0.0 MiB return a
好,就這些了,希望對(duì)你有幫助。
本文github地址:
歡迎補(bǔ)充
總結(jié)
以上是生活随笔為你收集整理的python profile_python程序之profile分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python阻塞和非阻塞_Python基
- 下一篇: python爬虫beautifulsou