为什么NetworkX中的Graph.copy()比copy.deepcopy(Graph)慢?

2024-04-25 13:56:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在广泛使用NetworkX进行研究,但我遇到了一些让我有点困惑(和担心)的事情。我一直在使用copy.deepcopy()复制图形,但刚刚意识到生成深度副本的Graph类has its own .copy() method

我决定用%timeit来看看我是否在妨碍自己,最后得到了一个有25个节点和66条边的图G的以下结果:

%timeit for x in range(100): copy.deepcopy(G)
80.5 ms ± 1.26 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit for x in range(100): G.copy()
93.4 ms ± 1.06 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

NetworkX的哪些不同之处需要更长的时间?这让我担心我做得不好,但到目前为止,我还没有遇到任何严重的问题,表明在这里使用copy.deepcopy()是错误的选择


Tags: ofindevnetworkxloopforrunsrange
1条回答
网友
1楼 · 发布于 2024-04-25 13:56:54

您可以自己查看源代码:[GitHub]: networkx/networkx - (master) networkx/networkx/classes/graph.py

根据[GitHub.NetworkX]: networkx.Graph.copy(同样的信息也出现在1stURL)(强调是我的):

The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an attribute is a container, that container is shared by the original an the copy. Use Python’s copy.deepcopy for new containers.

...

Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s copy.deepcopy)

...

Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the attributes. That is, any attributes that are containers are shared between the new graph and the original. This is exactly what dict.copy() provides.

Graph.copy(可能)所做的是额外的计算以保留内存

因此,如果您想要两个完全独立的图,您可以毫无问题地使用copy.deepcopy

相关问题 更多 >