Memory Profiler:Python代码的内存分析器
http://hao.jobbole.com/memory_profiler/
Memory_profiler是一个Python模块,可以监视一个进程的内存消耗,甚至可以一行一行的分析Python程序的内存消耗。它纯粹是由Python实现,用户可选psutil模块(强烈推荐)作为依赖。
示例
用@profile修饰你需要监视的函数,这里my_func函数分配列表a和b,然后删除b
Python123456789 | @profiledef my_func():a = [1] * (10 ** 6)b = [2] * (2 * 10 ** 7)del breturn a if __name__ == "__main__":my_func() |
运行脚本时需传入-m memory_profiler参数
1 | $python-mmemory_profilerexample.py |
以上命令输出如下
Python1 2 3 4 5 6 7 8 | Line# Mem usage Increment Line Contents ============================================== 3@profile 45.97MB0.00MBdefmy_func(): 513.61MB7.64MBa=[1]*(10**6) 6166.20MB152.59MBb=[2]*(2*10**7) 713.61MB-152.59MBdelb 813.61MB0.00MBreturna |
FAQ
Q:结果有多准确?
A:这个模块通过向操作系统内核查询当前进程所分配内存大小来获得内存消耗,可能与Python解释器实际使用的内存大小稍有区别。而且由于Python的垃圾回收器的影响,结果可能会在不同平台甚至不同运行之间有差别。
Q:在Windows下可用吗?
A:是的,但是你需要psutil模块
github主页:https://github.com/fabianp/memory_profiler
官方网站:https://pypi.python.org/pypi/memory_profiler
开源地址:https://github.com/fabianp/memory_profiler
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。