zoukankan      html  css  js  c++  java
  • Python 检查代码占用内存 工具和模块

    只介绍简单的使用, 更多使用方法请查看官方文档

    tracemalloc

    官方文档

    tracemalloc文档地址 

    使用

    import tracemalloc
    
    tracemalloc.start()
    
    # 运行程序
    main()
    
    snapshot = tracemalloc.take_snapshot()
    top_stats = snapshot.statistics('lineno')
    
    # 输出前10条测试结果
    print("[ Top 10 ]")
    for stat in top_stats[:10]:
        print(stat)

    statistics(key_type: strcumulative: bool=False)

    将统计信息作为 Statistic 实例分组依据 key_type :

    key_type

    描述

    'filename'

    文件名

    'lineno'

    文件名和行号

    'traceback'

    追溯

    如果 累积的 是 True ,累积跟踪的所有帧的内存块大小和计数,而不仅仅是最新帧。累积模式只能用于 key_type 等于 'filename' 和 'lineno' .

    结果按以下顺序从大到小排序: Statistic.size , Statistic.count 然后由 Statistic.traceback .

    memory_profiler

    官方文档

    https://pypi.org/project/memory-profiler/

    安装

    pip install -U memory_profiler

    在脚本外使用

    @profile
    def my_func():
        a = [1] * (10 ** 6)
        b = [2] * (2 * 10 ** 7)
        del b
        return a
    
    if __name__ == '__main__':
        my_func()

    运行:

    python -m memory_profiler example.py

    在文件中使用

    from memory_profiler import profile
    
    @profile
    def my_func():
        a = [1] * (10 ** 6)
        b = [2] * (2 * 10 ** 7)
        del b
        return a
    
    if __name__ == '__main__':
        my_func()

    运行:

    python example.py

    Heartrate

    项目地址

    https://github.com/alexmojaki/heartrate

    安装

    pip install --user heartrate

    使用

    # 在需要测试的文件中插入
    import heartrate; heartrate.trace(browser=True)

    欢迎补充

    目前使用过的, 还比较好使的是这些

  • 相关阅读:
    HDU
    HDU
    HDU
    HDU
    HDU
    P6146 [USACO20FEB]Help Yourself G 组合数学 DP
    CodeForces
    POJ
    【网络学习】集线器,交换机,路由器的作用
    【Python学习】深拷贝和浅拷贝
  • 原文地址:https://www.cnblogs.com/mswei/p/11951609.html
Copyright © 2011-2022 走看看