I'm studying heap algorithm. I thought a heap algorithm as a function will be slower than pure code. So I made a test. but I found functional code is much faster than pure code. I think this is very weird, and I don't know why.
enter image description here
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)
In CPython, local variable lookups are optimized more than global variable lookups, so putting code in a function often makes it run faster than module level code.
In a table of timings for common operations, you can see that read_local and write_local are faster than their global read/write counterparts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With