我有以下示例代码,它类似于我正在处理的主要代码。我看到的主要瓶颈在于函数调用 call_fun。有没有办法加快速度?..example:不使用字典对象 self._d 而是使用其他函数查找?在主代码中,“名称”列表非常大。您可以启用注释掉的打印语句以快速理解代码(...但如果您想打印输出,请务必将 i in range(500000) 更改为 i in range(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
10000009 function calls in 5.614 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 2.066 2.066 5.614 5.614 foo.py:1(<module>)
5000000 2.345 0.000 3.412 0.000 foo.py:11(call_fun)
5000000 1.067 0.000 1.067 0.000 foo.py:15(f_a)
1 0.135 0.135 0.135 0.135 {range}
1 0.000 0.000 0.000 0.000 foo.py:6(__init__)
2 0.000 0.000 0.000 0.000 {time.clock}
1 0.000 0.000 0.000 0.000 foo.py:5(A)
2 0.000 0.000 0.000 0.000 {getattr}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}