如何查看内存占用和运行速度

问题描述

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

 

 

转载于:https://www.cnblogs.com/wqbin/p/10398674.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值