print "no function"
start_time = time.time()
for i in range(10000):
for j in range(10000):
z = i*j
print z
print("--- %s seconds ---" % (time.time() - start_time))
# VS
def Function():
start_time = time.time()
for i in range(10000):
for j in range(10000):
z = i*j
print z
print("--- %s seconds ---" % (time.time() - start_time))
print "Function Call"
Function()
这是输出:
no function
99980001
--- 8.89359378815 seconds ---
Function Call
99980001
--- 4.64798092842 seconds ---
答案 0 :(得分:1)
从PythonInSpeed website我们可以读到:
在函数中,局部变量的访问速度比全局变量,内置函数和属性查找更快。因此,有时值得在内部循环中本地化变量访问。例如,random.shuffle()的代码使用行random = self.random来本地化访问。这使得洗牌循环不必重复查找self.random。在循环之外,增益很小,很少值得。