如何使用将用 numba 编译的代码有效地创建长度为 N 的元组? [英] How to efficiently create a tuple of length N with code that will compile with numba?

查看:82
本文介绍了如何使用将用 numba 编译的代码有效地创建长度为 N 的元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计时了两种方法来创建长度为 N 的元组.

I timed two ways to create a tuple of length N.

这非常快:

def createTuple():
    for _ in range(100000):
        tuplex = (0,) * 1000


CPU times: user 439 ms, sys: 1.01 ms, total: 440 ms
Wall time: 442 ms

这非常快,但不能用 Numba 编译:

This is very fast, but doesn't compile with Numba:

Invalid use of Function(<built-in function mul>) with argument(s) of type(s): (UniTuple(Literal[int](0) x 1), int64)

这要慢得多:

def createTuple():
    for _ in range(100000):
        tuplex = tuple(0 for _ in range(1000))

%time createTuple()


CPU times: user 5.28 s, sys: 3.28 ms, total: 5.29 s
Wall time: 5.29 s

并且也无法编译:

The use of yield in a closure is unsupported.

我对 Python 和 Numba 非常陌生.有没有办法使用 Numba 创建一个长度为 N(在编译时已知)的元组(希望有效地创建)?

I am very new to Python and Numba. Is there a way to get a tuple of length N (known at compile time) create - hopefully efficiently - with Numba?

推荐答案

来自 numba (0.50) 文档:

注意

不支持 tuple() 构造函数本身.

The tuple() constructor itself is NOT supported.

因此,在 numba 代码中,元组需要作为函数参数提供或初始化为文字,如 (0, 1, 2, 3).这是不幸的,因为这意味着涉及数组形状的操作需要 numba 中的元组,即使它们在常规 numpy 中与 int 数组一起工作正常:

So, in numba code, tuples need to be either supplied as function arguments or initialized as literals, like (0, 1, 2, 3). This is unfortunate, because it means that operations involving array shapes require tuples in numba, even though they work fine with int arrays in regular numpy:

shape = np.arange(1, 4)
np.zeros(shape) # OK for normal python code, not in an @njit function.

您必须重构代码才能在@njit 函数之外创建元组:

You'll have to refactor your code to have tuple creation outside the @njit function:

@njit
def foo(tup):
   ...

foo(tuple(np.zeros(100)))

不幸的是,tuple(np.zeros(100)) 相对较慢.

Unfortunately, tuple(np.zeros(100)) is relatively slow.

这篇关于如何使用将用 numba 编译的代码有效地创建长度为 N 的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆