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

标签 python python-3.x networkx

我一直在广泛使用 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/

相关文章:

python-3.x - 用 2d 数组索引 3d numpy 数组

python - 使用 Python 的内置 .csv 模块编写

python - Pandas /Numpy : Fastest way to create a ladder?

python - Web.py/没有名为 'utils' 的模块`

Python 多线程列表追加给出了意想不到的结果

django - 在 Django 中添加查询集中的所有值

Python:获取所有节点的度数,然后在networkx中绘制boxplot

python - 为什么我得到相同的图表?

python - 使用networkX的karger min cut算法运行时间非常慢

python - Python 是否定义了 "NaN > 0"的值?