How to estimate NetworkX graph memory usage?
Question:
How to check the amount of memory used by a NetworkX graph?
There is a method for checking the number of nodes and edges, but I could not find one for memory usage?
Answers:
You can get an estimate by adding up the size of the edge list and the size of the node list:
sys.getsizeof(G.edge) + sys.getsizeof(G.node)
In NetworkX 2.0 and later, G.edges
and G.nodes
return iterators, so taking the size of those directly doesn’t work, it just gives you the size of the iterator objects. You need it iterate over those objects and get the size of each edge and node and sum those to estimate the memory used by the graph.
import networkx as nx
import sys
G = nx.Graph()
# populate the graph with nodes and edges
edge_mem = sum([sys.getsizeof(e) for e in G.edges])
node_mem = sum([sys.getsizeof(n) for n in G.nodes])
print("Edge memory:", edge_mem)
print("Node memory:", node_mem)
print("Total memory:", edge_mem + node_mem)
How to check the amount of memory used by a NetworkX graph?
There is a method for checking the number of nodes and edges, but I could not find one for memory usage?
You can get an estimate by adding up the size of the edge list and the size of the node list:
sys.getsizeof(G.edge) + sys.getsizeof(G.node)
In NetworkX 2.0 and later, G.edges
and G.nodes
return iterators, so taking the size of those directly doesn’t work, it just gives you the size of the iterator objects. You need it iterate over those objects and get the size of each edge and node and sum those to estimate the memory used by the graph.
import networkx as nx
import sys
G = nx.Graph()
# populate the graph with nodes and edges
edge_mem = sum([sys.getsizeof(e) for e in G.edges])
node_mem = sum([sys.getsizeof(n) for n in G.nodes])
print("Edge memory:", edge_mem)
print("Node memory:", node_mem)
print("Total memory:", edge_mem + node_mem)