PyPy中是否有任何替代sys.getsizeof()?

问题描述:

我试图运行Python与PyPy(2.7)脚本,但我已经遇到了以下错误:PyPy中是否有任何替代sys.getsizeof()?

TypeError: sys.getsizeof() is not implemented on PyPy. 

A memory profiler using this function is most likely to give results 
inconsistent with reality on PyPy. It would be possible to have 
sys.getsizeof() return a number (with enough work), but that may or 
may not represent how much memory the object uses. It doesn't even 
make really sense to ask how much *one* object uses, in isolation 
with the rest of the system. For example, instances have maps, 
which are often shared across many instances; in this case the maps 
would probably be ignored by an implementation of sys.getsizeof(), 
but their overhead is important in some cases if they are many 
instances with unique maps. Conversely, equal strings may share 
their internal string data even if they are different objects---or 
empty containers may share parts of their internals as long as they 
are empty. Even stranger, some lists create objects as you read 
them; if you try to estimate the size in memory of range(10**6) as 
the sum of all items' size, that operation will by itself create one 
million integer objects that never existed in the first place. 

现在,我真的很需要的程序的执行过程中,检查一个嵌套的字典的大小,我可以在PyPy中使用sys.getsizeof()吗?如果不是,我将如何检查PyPy中嵌套对象的大小?

+0

“我真的很需要的程序的执行过程中,检查一个嵌套的字典的大小” - 'sys.getsizeof'不会一直是,即使在CPython中的工具。它不考虑对象所引用的其他对象的大小,例如字典键和值。 – user2357112

+0

很简单,你可以实现一个遍历嵌套字典的函数,并计算整个对象的累积大小。 http://*.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python –

+2

我想人们还是会问''sys.getsizeof()''即使文字墙更详细地解释了为什么它没有意义,并附有示例。 –

或者,也可以使用

import resource 
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss 

衡量你进程的内存使用情况作为你的程序正在执行时,的getrusage会给该方法的总的内存消耗以字节或千字节的数目。使用这些信息,您可以估计数据结构的大小,并且如果您开始使用机器总内存的50%,那么您可以采取一些措施来处理它。

+0

这是一种管理整个进程的内存消耗的方法,但它不会提供有关为特定对象分配的内存的信息。它可以用于我的具体情况。谢谢。 –