gpt4 book ai didi

Python : Functional code speed is faster than pure code speed. 为什么?

转载 作者:行者123 更新时间:2023-12-03 20:11:17 28 4
gpt4 key购买 nike

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

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)

最佳答案

在 CPython 中,局部变量查找比全局变量查找更优化,因此将代码放在函数中通常使其运行速度比模块级代码快。

table of timings for common operations ,您可以看到 read_local 和 write_local 比它们的全局读/写对应物更快。

关于Python : Functional code speed is faster than pure code speed. 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59963234/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com