在PyPy中有没有sys.getsizeof()的替代方法?

时间:2017-03-02 18:11:53

标签: python sizeof pypy

我正在尝试使用PyPy运行Python(2.7)脚本,但我遇到了以下错误:

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中检查嵌套对象的大小?

1 个答案:

答案 0 :(得分:3)

或者,您可以使用

衡量流程的内存使用情况
import resource
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

当您的程序正在执行时,getrusage将以字节数或千字节数给出进程的总内存消耗。使用这些信息,您可以估计数据结构的大小,如果您开始使用占机器总内存的50%,那么您可以采取一些措施来处理它。

相关问题