python碎碎念

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

2019-05-24  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读