【问题标题】:is there any alternative to sys.getsizeof() in PyPy?PyPy 中有没有 sys.getsizeof() 的替代方法?
【发布时间】:2017-03-02 18:11:52
【问题描述】:

我正在尝试使用 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 中嵌套对象的大小?

【问题讨论】:

  • “我真的需要在程序执行期间检查一个嵌套字典的大小” - 即使在 CPython 下,sys.getsizeof 也不是合适的工具。它不考虑对象引用的其他对象的大小,例如字典键和值。
  • 很简单,你可以实现一个函数,遍历嵌套的dict,计算整个对象的累积大小。 stackoverflow.com/questions/449560/…
  • 我想人们仍然会要求sys.getsizeof(),即使文字墙更详细地解释了为什么它没有意义,并附有示例。
  • @ArminRigo 这很清楚,但仍然必须有一种“足够好”的方法来检查对象的大小。
  • 在 PyPy 中无法获取对象的大小,这对我来说似乎很荒谬。

标签: python sizeof pypy


【解决方案1】:

或者,您可以使用

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

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

【讨论】:

  • 这是一种管理整个进程的内存消耗的方法,但它没有提供有关为特定对象分配的内存的信息。它适用于我的具体情况。谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-08-15
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
  • 2012-07-14
相关资源
最近更新 更多