简体   繁体   English

Python-内存中对象与磁盘上对象的大小

[英]Python - size of object in memory vs. on disk

Here is my example: 这是我的示例:

import numpy as np
test = [np.random.choice(range(1, 1000), 1000000) for el in range(1,1000)]

this object takes in memory: 该对象占用内存:

print(sys.getsizeof(test)/1024/1024/1024)
8.404254913330078e-06

something like 8 KB 大约8 KB

When I write it to disk 当我将其写入磁盘时

import pickle
file_path = './test.pickle'
with open(file_path, 'wb') as f:
    pickle.dump(test, f)

it take almost 8GB from ls -l command ls -l命令占用了将近8GB

Could somebody clarify why it take so little space in memory and some much on disk? 有人可以弄清楚为什么占用这么少的内存空间而占用那么多磁盘空间吗? I am guessing in memory numbers are not accurate. 我猜记忆中的数字不正确。

I am guessing in memory numbers are not accurate. 我猜记忆中的数字不正确。

Well, this would not explain 6 orders of magnitude in size, right? 好吧,这不能解释6个数量级的大小,对吗? ;) ;)

test is a Python list instance. test是一个Python list实例。 getsizeof will tell you the size of "a pointer", which is 64bit on your system together with some other attributes. getsizeof会告诉您“指针”的大小,该大小在您的系统上为64位以及其他一些属性。 But you will need to do a bit more to get all the stuff which is attached to this instance, inspecting each element (lists have no strict types in Python, so you can't simply do size_of_element * len(list) etc.). 但是您将需要做更多的工作来获取与此实例相关的所有内容,检查每个元素(列表在Python中没有严格的类型,因此您不能简单地执行size_of_element * len(list)等)。

Here is one resource: https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609 这是一种资源: https : //code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609

Here is another one: How do I determine the size of an object in Python? 这是另一个: 如何确定Python中对象的大小?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM