Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Functional code speed is faster than pure code speed. Why?

Tags:

python

heap

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)
like image 890
user9567849 Avatar asked Jan 25 '23 08:01

user9567849


1 Answers

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.

like image 198
Raymond Hettinger Avatar answered Jan 31 '23 23:01

Raymond Hettinger