首页 > 解决方案 > 为什么变量赋值比从 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)

标签: pythonarraysvariables

解决方案


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

推荐阅读