tl/dr:如何使用 Guppy 获取 python 程序的当前内存使用情况?有简单的命令吗?
我正在尝试使用 guppy 在 python 程序中跟踪内存使用情况。这是我第一次使用 guppy,所以我不太确定它的行为方式。我想要的是能够在模拟中随着“时间”的进展绘制总使用量。这是我可以做的一些基本代码:
from guppy import hpy
import networkx as nx
h = hpy()
L=[1,2,3]
h.heap()
> Partition of a set of 89849 objects. Total size = 12530016 bytes.
> Index Count % Size % Cumulative % Kind (class / dict of class)
> 0 40337 45 3638400 29 3638400 29 str
> 1 21681 24 1874216 15 5512616 44 tuple
> 2 1435 2 1262344 10 6774960 54 dict (no owner)
Run Code Online (Sandbox Code Playgroud)
但我只想知道当前的大小是多少(12530016 字节)。所以我希望能够调用类似的东西h.total()来获取总大小。如果这不作为一个简单的命令存在,我会感到震惊,但到目前为止,通过查看文档我还没有找到它。它可能已记录在案,只是不是我要找的地方。
x = h.heap()
x.size
Run Code Online (Sandbox Code Playgroud)
返回总大小。例如:
from guppy import hpy
import networkx as nx
h = hpy()
num_nodes = 1000
num_edges = 5000
G = nx.gnm_random_graph(num_nodes, num_edges)
x = h.heap()
print(x.size)
Run Code Online (Sandbox Code Playgroud)
印刷
19820968
Run Code Online (Sandbox Code Playgroud)
这与Total size报道的一致
print(x)
# Partition of a set of 118369 objects. Total size = 19820904 bytes.
# Index Count % Size % Cumulative % Kind (class / dict of class)
# 0 51057 43 6905536 35 6905536 35 str
# 1 7726 7 3683536 19 10589072 53 dict (no owner)
# 2 28416 24 2523064 13 13112136 66 tuple
# 3 516 0 1641312 8 14753448 74 dict of module
# 4 7446 6 953088 5 15706536 79 types.CodeType
# 5 6950 6 834000 4 16540536 83 function
# 6 584 0 628160 3 17168696 87 dict of type
# 7 584 0 523144 3 17691840 89 type
# 8 169 0 461696 2 18153536 92 unicode
# 9 174 0 181584 1 18335120 93 dict of class
# <235 more rows. Type e.g. '_.more' to view.>
Run Code Online (Sandbox Code Playgroud)