在运行数值积分器时,我注意到根据我从字典中提取字段的方式速度有明显的差异。
import numpy as np
def bad_get(mydict):
'''Extract the name field using get()'''
output = mydict.get('name', None)
return output
def good_get(mydict):
'''Extract the name field using if-else'''
if 'name' in mydict:
output = mydict['name']
else:
output = None
return output
name_dict = dict()
name_dict['name'] = np.zeros((5000,5000))
在我的系统上,我注意到以下差异(使用iPython)
%%timeit
bad_get(name_dict)
The slowest run took 7.75 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 247 ns per loop
与...相比
%%timeit
good_get(name_dict)
1000000 loops, best of 3: 188 ns per loop
这看起来似乎是一个细微的差别,但对于某些数组来说,这种差别似乎更加显著。这种行为的原因是什么,我是否应该改变对get()
函数的使用方式?
mydict.get("name")
替换为mydict["name"]
,捕获KeyError
并在那里分配None
。 - Jan Vlcinsky