非常大的就地numpy阵列操作:numba、pythran还是其他?

2024-05-16 11:44:23 发布

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

tI需要在非常大的阵列(数百万个条目)上执行操作,这些阵列的累积大小接近可用内存。 我理解,当使用numpy(如a=a*3+b-c**2)执行简单操作时,会创建几个临时数组,从而占用更多内存

由于我计划在内存占用的限制下工作,恐怕这种简单的方法行不通。所以我想用正确的方法开始我的发展

我知道像numbapythran这样的包在操作数组时可以帮助提高性能,但我不清楚它们是否可以自动处理就地操作,避免临时对象

作为一个简单的示例,我必须在大型阵列上使用一个函数:

def find_bins(a, indices):
    global offset, width, nstep
    i = (a-offset) *nstep/ width 
    i = np.where(i<0,0,i)
    i = np.where(i>=nstep,nstep, i)
    indices[:] = i.astype(int)

混合了算术运算和对numpy函数的调用

使用numba或pythran(或其他东西)编写这样的函数有多容易? 每种情况的利弊是什么

谢谢你的提示

ps:我知道numexpr,但我不确定它是否方便或适合于比单个算术表达式更复杂的函数


Tags: 方法函数内存numpynpti算术数组
2条回答

使用numexpr。例如:

import numexpr
numexpr.evaluate("a+b*c", out=a)

这可以帮助您避免tmp变量,您可以参考高性能Python、M.G、I.O.

Pythran通过设计避免了许多临时数组。对于您所指的简单表达式,应该是


#pythran export find_bins(float[], int[], float, float, int)
import numpy as np
def find_bins(a, indices, offset, width, nstep):
    i = (a-offset) *nstep/ width #
    i = np.where(i<0,0,i)
    i = np.where(i>=nstep,nstep, i)
    indices[:] = i.astype(int)

这既避免了临时的,又加快了计算速度

并不是说您应该在这里使用np.clip函数,Pythran也支持它

相关问题 更多 >