简体   繁体   中英

Speeding up random minimum spanning tree in networkx?

Here's a bit of code whose goal is to build a random spanning tree using greedy and random edge weights. It runs much slower than I would like it to. Any tips for ways to speed it up?

Both the randomly generating weights and the sampling of a minimum spanning tree are slow... the first is especially weird to me, because there are only 179400 edges and np.random.uniform(0,1,179400) executes very quickly.

(Here slow means on the order of seconds.)

(I'm happy to use something other than networkx,but it's not preferable.)

import numpy as np
import networkx as nx

graph = nx.grid_graph([300, 300])

for edge in graph.edges():
    graph.edges[edge]["weight"] = np.random.uniform(0, 1)

tree = nx.minimum_spanning_tree(graph)

If bulk production of random numbers is quicker in your tests, then just do that.

rand = np.random.uniform(0, 1, graph.edges.size())
i = 0
for edge in graph.edges():
    graph.edges[edge]["weight"] = rand[i]
    i += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM