下面的示例代码与我正在处理的主代码类似。我看到的主要瓶颈是调用call-fun函数。有没有办法加快速度。。示例:不使用dictionary对象self.\d而使用其他对象进行函数查找?在主代码中,“名称”列表相当大。为了快速理解代码(。。。但如果要打印输出,请确保将范围内的i(500000)更改为范围内的i(1)import time
names = [ ('f_a', ([1,1],)), ('f_b', ([3,4],) ) ]
class A(object):
def __init__(self):
self._d = {}
for n in names:
self._d[n[0]] = getattr(self, n[0])
def call_fun(self, k):
#print " In call_fun: k: ", k
return self._d[k[0]](*k[1])
def f_a(self, vals):
#print " I am here in f_a.. vals=", vals
v = 2*vals
return v
def f_b(self, vals):
v = 3*vals
return v
# Run the code
start = time.clock()
a = A()
print "names[0]:", names[0]
for i in range(5000000):
a.call_fun((names[0]))
print "done, elapsed wall clock time (win32) in seconds: " , time.clock() - start
以下是分析输出:python -m cProfile --sort cumulative foo.py
^{pr2}$