同一代码的python不同性能

Python different performance for identical code

本问题已经有最佳答案,请猛点这里访问。

我偶然发现了一些毫无意义的东西。我有这个python代码,它为循环做了2个简单的操作,并且只测量执行时间。然而,我发现从函数调用的完全相同的代码需要一半的时间。有人能解释为什么吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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()

下面是输出:

1
2
3
4
5
6
no function
99980001
--- 8.89359378815 seconds ---
Function Call
99980001
--- 4.64798092842 seconds ---


从pythoninspeed网站我们可以看到:

In functions, local variables are accessed more quickly than global variables, builtins, and attribute lookups. So, it is sometimes worth localizing variable access in inner-loops. For example, the code for random.shuffle() localizes access with the line, random=self.random. That saves the shuffling loop from having to repeatedly lookup self.random. Outside of loops, the gain is minimal and rarely worth it.