python - 为什么变量赋值比从 python 中的数组调用更快?
问题描述
我一直在为我正在构建的程序优化一些欧几里得距离变换计算。作为序言,除了我一直在参加的一些 MOOC 课程之外,我几乎没有接受过计算机科学方面的正式培训。
我通过 Python 中的经验测试了解到,将值分配给单个变量并对它们执行操作比对数组执行操作要快。这个观察结果可以复制给其他人吗?
如果是这样,有人可以更深入地解释为什么这两种语法形式之间存在如此大的速度差异吗?
请参阅下面的一些示例代码。
import numpy as np
from math import sqrt
import time
# Numpy array math
def test1(coords):
results = []
for coord in coords:
mins = np.array([1,1,1])
# The three lines below seem faster than np.linalg.norm()
mins = (coord - mins)**2
mins = np.sum(mins)
results.append(sqrt(mins))
# Individual variable assignment math
def test2(coords):
results = []
for point in coords:
z, y, x = 1, 1, 1
z = (point[0] - z)**2
y = (point[1] - y)**2
x = (point[2] - x)**2
mins = sqrt(z + y + x)
results.append(mins)
a = np.random.randint(0, 10, (500000,3))
t = time.perf_counter()
test1(a)
print ("Test 1 speed:", time.perf_counter() - t)
t = time.perf_counter()
test2(a)
print ("Test 2 speed:", time.perf_counter() - t)
- 测试1速度:3.261552719 s
- 测试2速度:0.716983475 s
解决方案
Python 操作和内存分配通常比 Numpy 高度优化的向量化数组操作慢得多。由于您正在遍历数组并分配内存,因此您不会获得 Numpy 提供的任何好处。在您的第一个中尤其糟糕,因为它会导致分配过多的小数组。
将您的代码与将所有操作卸载到 Numpy 的代码进行比较,而不是让 Python 一个一个地执行操作:
def test3(coords):
mins = (coords - 1)**2
results = np.sqrt(np.sum(mins, axis=1))
return results
在我的系统上,这会导致:
Test 1 speed: 4.995761550962925
Test 2 speed: 1.3881473205983639
Test 3 speed: 0.05562112480401993
推荐阅读
- git - GIT:查找补丁分支的连接点
- autodesk-forge - 我可以使用 Autodesk Forge 翻译包含内部组件(其他 .iam 文件)的 Inventor 文件 (.iam) 吗?
- sql-server - 如何将存储在列中的 xml 中的 id 与另一个表中的列中的 id 连接起来
- java - 共享元素转换图像视图一些时间尺度和一些时间不是,我使用导航组件、recyclerview、片段和线圈
- json - 响应序列化错误,如何解决?
- tomcat - 在不锁定会话的情况下无法访问 VaadinSession 或 UI 中的状态
- apache-kafka - confluent kafka - 速率限制
- git - 提交后如何修复丢失 git blame 功能?(EOL 冲突)
- java - docker-compose 连接到 postgres 服务器时出现问题
- variables - Kotlin 最佳实践:对象字段的 val