Python:函数代码速度比纯代码速度快。为什么?

2024-10-08 18:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学习堆算法。 我认为堆算法作为一个函数会比纯代码慢。 所以我做了一个测试。但我发现函数代码比纯代码快得多。 我觉得这很奇怪,我不知道为什么

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)

Tags: 函数代码in算法forlentimerange

热门问题