python查看函数消耗的内存_如何查看内存占用和运行速度

问题描述

1、Python开发的程序在使用过程中很慢,想确定下是哪段代码比较慢;

2、Python开发的程序在使用过程中占用内存很大,想确定下是哪段代码引起的;

解决方案

使用profile分析分析cpu使用情况

可以使用profile和cProfile对python程序进行分析,这里主要记录下cProfile的使用,profile参考cProfile即可。

#slots_test.py

classFoobar(object):__slots__=('x')def __init__(self, x):

self.x=xdefmain():

f= [Foobar(42) for i in range(1000000)]if __name__ == "__main__":

main()

1.简单查看

python -m cProfile slots_test.py

1353331-20190218233035842-1705832503.png

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()"

1353331-20190218233636441-169119183.png

结果说明

ncalls : 函数的被调用次数

tottime :函数总计运行时间,除去函数中调用的函数运行时间

percall :函数运行一次的平均时间,等于tottime/ncalls

cumtime :函数总计运行时间,含调用的函数运行时间

percall :函数运行一次的平均时间,等于cumtime/ncalls

filename:lineno(function) 函数所在的文件名,函数的行号,函数名

使用memory_profiler分析内存使用情况

需要安装memory_profiler :

pip installpsutil

pipinstall memory_profiler

1.不导入模块

1353331-20190218234238652-1188140257.png

python -m memory_profiler slots_test.py

1353331-20190218234353185-820242365.png

不加 -m memory_profiler会报错

1353331-20190218234551975-1992406703.png

2.导入模块

#slots_test.py

from memory_profiler importprofileclassFoobar(object):__slots__=('x')def __init__(self, x):

self.x=x

@profiledefmain():

f= [Foobar(42) for i in range(1000000)]if __name__ == "__main__":

main()

python slots_test.py

1353331-20190218234919732-523246809.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值