我一直在广泛使用 NetworkX 进行我的研究,但我遇到了一些让我有点困惑(和担忧)的事情。我一直在使用 copy.deepcopy()
复制图形,但刚刚意识到图形类 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()
是错误的选择。
最佳答案
可以自己看源码:[GitHub]: networkx/networkx - (master) networkx/networkx/classes/graph.py .
根据 [GitHub.NetworkX]: networkx.Graph.copy (同样的信息也存在于第一个st URL)(强调是我的):
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(可能)所做的是为了保留内存而进行的额外计算。
因此,如果您想要 2 个完全独立的图表,您可以毫无问题地使用 copy.deepcopy。
关于python - 为什么 Graph.copy() 比 NetworkX 中的 copy.deepcopy(Graph) 慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60310123/