在运行此代码后,我不希望看到下面显示的输出,并想知道是否有人可以解释它。
第9行将文件读入内存,运行memory_profiler显示此行的内存使用量增加了374 MB。
但是在第11行,使用sys.getsizeof()打印文件对象的大小。任何人都可以解释为什么对象的大小似乎大于读取后记录的内存使用量增量?
import os
import math
import sys
from memory_profiler import memory_usage
@profile
def my_func():
with open('f.csv', 'r', encoding='utf8') as content_file:
content = content_file.read()
size = str(round(sys.getsizeof(content)/1000000))
print('The size of the file object is: ' + size + ' MB')
if __name__ == '__main__':
my_func()
输出
The size of the file object is: 392 MB
Filename: memorydemo.py
Line # Mem usage Increment Line Contents
================================================
6 17.898 MiB 0.000 MiB @profile
7 def my_func():
8 17.898 MiB 0.000 MiB with open('f.csv', 'r', encoding='utf8') as content_file:
9 392.082 MiB 374.184 MiB content = content_file.read()
10 392.090 MiB 0.008 MiB size = str(round(sys.getsizeof(content)/1000000))
11 392.090 MiB 0.000 MiB print('The size of the file object is: ' + size + ' MB')
更新
感谢mkrieger1和一些程序员老兄解释:
1048576 * 374.184 = 392360361字节
这解释了sys.getsizeof()
的输出