python - Python:函数式代码速度比纯代码速度更快。为什么?
问题描述
我正在研究堆算法。我认为堆算法作为函数会比纯代码慢。所以我做了一个测试。但我发现函数式代码比纯代码快得多。我觉得这很奇怪,我不知道为什么。
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 中,局部变量查找比全局变量查找更优化,因此将代码放在函数中通常使其运行速度比模块级代码快。
在常用操作的时序表中,您可以看到 read_local 和 write_local 比它们的全局读/写对应物更快。
推荐阅读
- performance - Hive JDBC 连接没有通过 JMeter 发生
- c - 使用 for 循环制作 Loading... 动画
- elasticsearch - 是否可以通过过滤器在 Elastic Search 中添加数据?
- javascript - 如何组合两个数组中的值?
- javascript - React-Admin TextField 和 TextInput 不显示标签和 css
- python-3.x - 如何清除使用 Tkinter label().place() 函数显示的文本
- flutter - 用于空值的空检查运算符
- python - 如何在 Kivy 的 BoxLayout 中保持按钮比例
- asp.net - 从 Excel 文件中提取数据以在 ASP.net 核心应用程序中使用它
- python - 我在我的 python 3.6 中安装了 tensorflow,但我无法将它导入到我在可视化代码工作室的项目中