__slots__Python中的目的是什么- 特别是关于我何时想要使用它,何时不想使用它?
我想知道我的Python应用程序的内存使用情况,并且特别想知道哪些代码块/部分或对象占用了大部分内存.Google搜索显示商业广告是Python Memory Validator(仅限Windows).
我没有尝试任何人,所以我想知道哪一个是最好的考虑:
提供大部分细节.
我必须对代码进行最少或不做任何更改.
我最近对算法感兴趣,并开始通过编写一个简单的实现,然后以各种方式优化它来探索它们.
我已经熟悉用于分析运行时的标准Python模块(对于大多数事情我已经发现IPython中的timeit魔术功能已足够),但我也对内存使用感兴趣,所以我也可以探索这些权衡(例如,缓存先前计算的值表的成本与根据需要重新计算它们的成本.是否有一个模块可以为我分析给定函数的内存使用情况?
我想知道在调用函数期间分配的最大RAM量是多少(在Python中).关于跟踪RAM使用的SO还有其他问题:
但是那些似乎允许你在heap()调用方法(在guppy的情况下)时更多地跟踪内存使用情况.但是,我想要跟踪的是外部库中的一个函数,我无法修改它,并且它会增长以使用大量的RAM,但是一旦函数执行完成就会释放它.有没有办法找出函数调用期间使用的RAM总量是多少?
当我运行以下代码时,我分别得到3和36作为答案.
x ="abd"
print len(x)
print sys.getsizeof(x)
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释一下它们之间有什么区别吗?
在Python中,与包含该类相同属性的字典相比,为类实例创建的字典很小:
import sys
class Foo(object):
def __init__(self, a, b):
self.a = a
self.b = b
f = Foo(20, 30)
Run Code Online (Sandbox Code Playgroud)
使用Python 3.5.2时,以下调用getsizeof生成:
>>> sys.getsizeof(vars(f)) # vars gets obj.__dict__
96
>>> sys.getsizeof(dict(vars(f))
288
Run Code Online (Sandbox Code Playgroud)
288 - 96 = 192 字节已保存!
但是,另一方面,使用Python 2.7.12,相同的调用返回:
>>> sys.getsizeof(vars(f))
280
>>> sys.getsizeof(dict(vars(f)))
280
Run Code Online (Sandbox Code Playgroud)
0 保存的字节数
在这两种情况下,词典显然具有完全相同的内容:
>>> vars(f) == dict(vars(f))
True
Run Code Online (Sandbox Code Playgroud)
所以这不是一个因素.此外,这也仅适用于Python 3.
那么,这里发生了什么?为什么__dict__Python 3中实例的大小如此之小?
我正在尝试使用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 …Run Code Online (Sandbox Code Playgroud) python ×7
profiling ×3
memory ×2
class ×1
dictionary ×1
oop ×1
performance ×1
pypy ×1
python-2.7 ×1
python-3.x ×1
sizeof ×1
slots ×1