Python:函数代码速度比纯代码速度快。为什么?
我在学习堆算法。 我认为堆算法作为一个函数会比纯代码慢。 所以我做了一个测试。但我发现函数代码比纯代码快得多。 我觉得这很奇怪,我不知道为什么Python:函数代码速度比纯代码速度快。为什么?,python,heap,Python,Heap,我在学习堆算法。 我认为堆算法作为一个函数会比纯代码慢。 所以我做了一个测试。但我发现函数代码比纯代码快得多。 我觉得这很奇怪,我不知道为什么 导入时间 def heapify(堆): 对于范围(1,len(heap))中的i: 而我0: 根=整数((i-1)/2) 如果heap[i]
导入时间
def heapify(堆):
对于范围(1,len(heap))中的i:
而我0:
根=整数((i-1)/2)
如果heap[i]
在CPython中,局部变量查找比全局变量查找更优化,因此将代码放入函数中通常会使其运行速度比模块级代码快
在a中,您可以看到读本地和写本地的速度比全局读/写的速度快。您为什么会这样想?通常,局部函数范围内的代码比完全使用全局范围的代码要快,因为局部变量查找速度更快。注意,这不是通常意义上的“功能性”。在任何情况下,你又一次问,为什么你认为它在一个函数中会变慢?一个(非常)长的函数会比一个等价的(但要短得多)函数更快,调用多个其他函数来执行它的子任务吗?或者更具体地说,短函数(小局部变量池)中的函数调用开销+局部变量查找是否大于具有大变量池的函数中的局部变量查找?还是可以忽略不计?我意识到这可能是一个独立的(部分无关的)问题。
import time
def heapify(heap):
for i in range(1, len(heap)):
while i != 0:
root = int((i - 1) / 2)
if heap[i] < heap[root]:
tmp = heap[i]
heap[i] = heap[root]
heap[root] = tmp
i = root
else:
break
return heap
heap = [5,2,5,0,11,12,7,8,10] * 10000
a = time.time()
for i in range(1, len(heap)):
while i != 0:
root = int((i - 1) / 2)
if heap[i] < heap[root]:
tmp = heap[i]
heap[i] = heap[root]
heap[root] = tmp
i = root
else:
break
b = time.time()
print("func code time :", b-a)
heap2 = [5,2,5,0,11,12,7,8,10] * 10000
a = time.time()
heap2 = heapify(heap2)
b = time.time()
print("pure code time :", b-a)
print(heap == heap2)