转载自: http://www.oschina.net/translate/python-memory-issues-tips-and-tricks
Python 打算删除大量涉及像C和C++语言那样的复杂内存管理。当对象离开范围,就会被自动垃圾收集器回收。然而,对于由 Python 开发的大型且长期运行的系统来说,内存管理是不容小觑的事情。 在这篇博客中,我将会分享关于减少 Python 内存消耗的方法和分析导致内存消耗/膨胀根源的问题。这些都是从实际操作中总结的经验,我们正在构建 Datos IO 的 RecoverX 分布式备份和恢复平台,这里主要要介绍的是在 Python(在 C++ ,Java 和 bash 中也有一些类似的组件) 中的开发。 |
无若
|
Python 垃圾收集
|
1
2
3
|
>>>
import
resource
>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
4332
|
对象(objgraph)
‘objgraph’ 是一个实用模块,可以展示当前内存中存在的对象
[objgraph 文档和实例地址: https://mg.pov.lt/objgraph/]
来看看objgraph的简单用法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
import
objgraph
import
random
import
inspect
class
Foo(
object
):
def
__init__(
self
):
self
.val
=
None
def
__str__(
self
):
return
“foo – val: {
0
}”.
format
(
self
.val)
def
f():
l
=
[]
for
i
in
range
(
3
):
foo
=
Foo()
#print “id of foo: {0}”.format(id(foo))
#print “foo is: {0}”.format(foo)
l.append(foo)
return
l
def
main():
d
=
{}
l
=
f()
d[‘k’]
=
l
print
“
list
l has {
0
} objects of
type
Foo()”.
format
(
len
(l))
objgraph.show_most_common_types()
objgraph.show_backrefs(random.choice(objgraph.by_type(‘Foo’)),
filename
=
“foo_refs.png”)
objgraph.show_refs(d, filename
=
‘sample
-
graph.png’)
if
__name__
=
=
“__main__”:
main()
python test1.py
list
l has
10000
objects of
type
Foo()
dict
10423
Foo
10000
————> Guilty as charged!
tuple
3349
wrapper_descriptor
945
function
860
builtin_function_or_method
616
method_descriptor
338
weakref
199
member_descriptor
161
getset_descriptor
107
|
注意,我们在内存中还持有10,423个‘dict’的实例对象。
花间_拾零
翻译于 3周前
0人顶
顶 翻译的不错哦!
可视化objgraph依赖项
|
1
2
|
objgraph.show_backrefs(random.choice(objgraph.by_type(‘Foo’)),
filename
=
“foo_refs.png”)
|
在这一案例中, 我们查看了Foo类型的随机对象。我们知道该特定对象被保存在内存中,因其引用链接在指定范围内。
有时,以上技巧能帮助我们理解,为什么当我们不再使用某对象时,Python垃圾回收器没有将垃圾回收。
难处理的是,有时候我们会发现Foo()占用了很多内存的类。这时我们可以用heapy()来回答以上问题。
花间_拾零
翻译于 3周前
0人顶
顶 翻译的不错哦!
Heapy
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
from
guppy
import
hpy
def
dump_heap(h, i):
“””
@param h: The heap (
from
hp
=
hpy(), h
=
hp.heap())
@param i: Identifier
str
“””
print
“Dumping stats at: {
0
}”.
format
(i)
print
‘Memory usage: {
0
} (MB)’.
format
(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
/
1024
)
print
“Most common types:”
objgraph.show_most_common_types()
print
“heap
is
:”
print
“{
0
}”.
format
(h)
by_refs
=
h.byrcs
print
“by references: {
0
}”.
format
(by_refs)
print
“More stats
for
top element..”
print
“By clodo (
class
or
dict
owner): {
0
}”.
format
(by_refs[
0
].byclodo)
print
“By size: {
0
}”.
format
(by_refs[
0
].bysize)
print
“By
id
: {
0
}”.
format
(by_refs[
0
].byid)
|
无若
翻译于 3周前
0人顶
顶 翻译的不错哦!
减少内存消耗小技巧在这一部分,我会介绍一些自己发现的可减少内存消耗的小窍门. Slots当你有许多对象时候可以使用Slots。Slotting传达给Python解释器:你的对象不需要动态的字典(从上面的例子2.2中,我们看到每个Foo()对象内部包含一个字典) 用slots定义你的对象,让python解释器知道你的类属性/成员是固定的.。这样可以有效地节约内存! 参考以下代码:
在这个例子中,减少了60%的内存消耗! 更多Slotting的信息,请点击链接: http://www.elfsternberg.com/2009/07/06/python-what-the-hell-is-a-slot/ |
花间_拾零
|
驻留:谨防驻留字符串!Python会记录如字符串等不可改变的值(其每个值的大小依赖于实现方法),这称为驻留。
这是由python解析器完成的,这样做可以节省内存,并加快比较速度。例如,如果两个字符串拥有相同的ID或引用--他们就是全等的。 然而,如果你的程序创建了许多小的字符串,你的内存就会出现膨胀。 生成字符串时使用Format来代替“+”接下来,在构造字符串时,使用Format来代替“+”构建字符串。 亦即,
在我们的系统中,当我们将某些字符串构造从“+”变为使用format时,内存会明显被节省。 |
wnull
|
关于系统级别
|
花间_拾零
|
总结
|