标准库有三种分析方法(cProfile和profile,hotshot)以及不计其数的第三方可视化工具,转化器,以及诸如此类的东西。
memory_profiler模块(与psutil一起使用)
psutil这模块实现了很多Linux命令的主要功能,如:ps, top, lsof, netstat, ifconfig, who, df, kill, free 等等。
from memory_profiler import profile from memory_profiler import memory_usage import time @profile def my_func(): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7) del b return a def cur_python_mem(): mem_usage = memory_usage(-1, interval=0.2, timeout=1) return mem_usage def f(a, n=100): time.sleep(1) b = [a] * n time.sleep(1) return b if __name__ == '__main__': a = my_func() print cur_python_mem() print "" print memory_usage((f, (1,), {'n': int(1e6)}), interval=0.5)