美文网首页python碎碎念
python查看系统内存和自身个模块占用内存

python查看系统内存和自身个模块占用内存

作者: 你说你要一场 | 来源:发表于2019-05-24 19:13 被阅读0次

    查看系统内存:

    >>> import os,psutil
    >>> info = psutil.virtual_memory()
    >>> info
    svmem(total=8293138432, available=6058491904, percent=26.9, used=1928695808, free=4820652032, active=2230849536, inactive=853688320, buffers=150827008, cached=1392963584, shared=26759168)
    >>> 8293138432/1024/1024
    7908.953125
    >>> 1928695808/1024/1024
    1839.34765625
    
    

    查看自身函数占用的内存:

    pip install memory_profiler
    
    from hashlib import sha1
    import sys
    
    @profile
    def my_func():
        sha1Obj = sha1()
        with open(sys.argv[1], 'rb') as f:
            while True:
                buf = f.read(10 * 1024 * 1024)
                if buf:
                    sha1Obj.update(buf)
                else:
                    break
    
        print(sha1Obj.hexdigest())
    
    
    if __name__ == '__main__':
        my_func()
    

    memory_profiler是利用python的装饰器工作,在进行测试的函数上添加装饰器。
    运行方式:

    python3 -m memory_profiler main.py
    

    相关文章

      网友评论

        本文标题:python查看系统内存和自身个模块占用内存

        本文链接:https://www.haomeiwen.com/subject/sfinzqtx.html