查看 Python程序或对象的内存占用

  • 1.查看当前程序的内存占用——psutil 库
  • 2.查看Python对象的内存占用——sys库
  • a.查看 DataFrame 的内存占用
  • b.查看 numpy 的内存占用


1.查看当前程序的内存占用——psutil 库

导入 psutil 库

import psutil
import os

查看当前 Python 程序的内存占用

print(u'当前进程的内存使用:%.4f GB' % (psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / 1024) )
> 当前进程的内存使用:0.6119 GB

查看电脑的总的内存信息

info = psutil.virtual_memory()
info

> svmem(total=8506298368, available=3768840192, percent=55.7, used=4737458176, free=3768840192)

将信息打印出来

print( u'电脑总内存:%.4f GB' % (info.total / 1024 / 1024 / 1024) )
print(u'当前使用的总内存占比:',info.percent)
print(u'cpu个数:',psutil.cpu_count())

> 电脑总内存:7.9221 GB
> 当前使用的总内存占比: 55.7
> cpu个数: 8

2.查看Python对象的内存占用——sys库

导入sys库

import sys
a.查看 DataFrame 的内存占用

sys库查看

print(sys.getsizeof(df) / 1024 / 1024, 'MB')
> 15.755158424377441 MB

pandas自带方法,结果近似

# df.memory_usage()显示 df 的每个特征(不是元素)所占用的内存,是个Series
print(df.memory_usage().sum() / 1024 / 1024 , 'MB')
> 15.754988670349121 MB
b.查看 numpy 的内存占用

生成 numpy 对象

a = np.random.rand(100000, 1000) 
print(sys.getsizeof(a) / 1024 / 1024, 'MB')
> 762.9395599365234 MB

# 每个元素8个字节(B),总内存的计算方法为 100000 x 1000 x 8 / 1024 / 1024 = 762.939453125‬
a.itemsize
> 8
  1. 数组的每个元素的大小是一致的,8个字节,当元素数量增大10倍时,数组所占内存也会增大10倍
  2. 当shape为(1000000, 10000) 时,内存超过70G,报错MemoryError: Unable to allocate 74.5 GiB for an array with shape (1000000, 10000) and data type float64
    而当shape为(100000, 10000) 时,内存大概7G,超过我的电脑的运行内存,但为何最后也创建数组了???