使用heapy追踪Django应用中的内存泄漏
我在这里找到了一个很棒的帖子,讲解了如何在Django中设置heapy工具:http://www.toofishes.net/blog/using-guppy-debug-django-memory-leaks/
我执行了hp.setref()命令,现在过了一段时间后,我也得到了hp.heap()的数据:
>>> hp.heap()
Partition of a set of 12075 objects. Total size = 1515496 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 4048 34 339656 22 339656 22 str
1 3112 26 269368 18 609024 40 tuple
2 171 1 169992 11 779016 51 dict (no owner)
3 1207 10 144440 10 923456 61 list
4 49 0 102040 7 1025496 68 dict of module
5 591 5 66984 4 1092480 72 unicode
6 498 4 59760 4 1152240 76 function
7 433 4 51960 3 1204200 79 types.CodeType
8 57 0 50480 3 1254680 83 type
9 36 0 31584 2 1286264 85 dict of class
那么接下来该怎么办呢?我应该从这个输出中理解什么?我该如何开始追踪这些'str'和'tuple'对象属于哪里?
通过get_rp,我得到了以下输出:
>>> hp.heap().get_rp()
Reference Pattern by <[dict of] class>.
0: _ --- [-] 12000 (0xd1d340 | 0xd88b50 | 0xf63f00 | __builtin__.Struct | __...
1: a [-] 137 dict (no owner): 0x761c30*160, 0x7655d0*1491, 0x781640*9...
2: aa ---- [-] 45 dict of django.db.models.options.Options: 0xcf3110...
3: a3 [-] 45 django.db.models.options.Options: 0xcf3110, 0xf0bb10...
4: a4 ------ [-] 140 dict of django.db.models.related.RelatedObject: 0x10bec...
5: a5 [-] 140 django.db.models.related.RelatedObject: 0xf14450...
6: a6 -------- [-] 63 dict of django.db.models.fields.related.ForeignKey: 0x...
7: a7 [+] 63 django.db.models.fields.related.ForeignKey: 0xf0e690...
8: a5b ------- [-] 7 dict of django.db.models.fields.related.OneToOneField: ...
9: a5ba [+] 7 django.db.models.fields.related.OneToOneField: 0x15447...
现在可以正确推测是Django在泄漏内存吗?但是那些没有拥有者的dict又是什么呢?
1 个回答
0
我对heapy没有什么经验,但根据我的经验,Django(还有大多数其他Python程序)通常不会出现内存泄漏,不过它们在清理内存方面做得也不够完美,可能有些人会觉得不够好。
另外,Django有一些设置会让它为了诊断目的消耗更多内存。比如,把DEBUG设置为True时,它会保存所有的SQL查询,这样程序运行得越久,使用的内存就会越多。
更新:你的问题不在于Python代码。看看heapy给你的总结:那里的总内存大小是1.5Mb!当Python程序真的出现内存泄漏时,最常见的原因是某个C扩展有问题。你在Django进程中运行的有没有C扩展呢?