在内存管理和计算速度方面,哪个是最有效的?在
下面的简单测试表明,与通过属性表进行字典查找相比,在节点中以python对象存储属性稍微好一些。由于内存的分配方式,这种情况会一直存在吗?在
作为测试,我构建了一个简单的示例:
class country():
def __init__(self, name, gdp):
self.name = name
self.gdp = gdp
def __repr__(self):
return str(self.name)
#Country Objects
countries = dict()
countries['AUS'] = country('AUS', 2000)
countries['USA'] = country('USA', 10000)
countries['ZWE'] = country('ZWE', 13)
#Attribute Dictionary
gdp = dict()
gdp['AUS'] = 2000
gdp['USA'] = 10000
gdp['ZWE'] = 13
构建网络:
^{pr2}$在IPython中运行%timeit:
G1f()
#Lookup Data from Strings Network
def G1f():
for n in G1.nodes():
print "Node: %s" % n
print "\tGDP: %s" % gdp[n]
%timeit G1f
G1f()的输出:
10000000 loops, best of 3: 26.4 ns per loop
G2f()
#Lookup Data from Objects
def G2f():
for n in G2.nodes():
print "Node: %s" % n.name
print "\tGDP: %s" % n.gdp
%timeit G2f
G2f()的输出
10000000 loops, best of 3: 21.8 ns per loop
更新
G3f()[来自答案]
G3 = nx.Graph()
for c,v in gdp.items():
G3.add_node(c, gdp=v)
def G3f():
for n,d in G3.nodes(data=True):
print "Node: %s" % n
print "\tGDP: %s" % d['gdp']
G13f()的输出:
10000 loops, best of 3: 63 µs per loop
也可以使用如下节点属性:
我不清楚考试时间安排是否很重要。除非这是一个非常大的问题(也许有一天每个人都会有自己的国家!)在速度和内存上可能没有太大的差别。我怀疑创建许多小型自定义对象(country())的开销最终会占用更多的内存和时间。在
相关问题 更多 >
编程相关推荐