在 Numba 优化的 Python 中将类对象作为函数参数传递 [英] Passing a class object as a function argument, in Numba optimized Python

查看:63
本文介绍了在 Numba 优化的 Python 中将类对象作为函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个类对象传递给一个函数.我可以让它工作,但我想知道是否有我可以分配的类型?我有一个我正在尝试做的最小"示例.

I want to pass a class object to a function. I can make it work, but I am wondering if there is a type I can assign it? I have a "minimal" example of what I am trying to do.

spec = [("a", float64),("b",float64)]
@jitclass(spec)
class SOMETHING_3():
    def __init__(self):
        self.a = 1.1
        self.b = 2.3

    def sum(self):
        return self.a + self.b


@jit(float64(float64, XXX), nopython = True)
def get_sum_3(c, someobj):
    d = 0
    for i in range(1000):
        for j in range(1000):
            d += c + someobj.sum()
    return d   

如果我删除显式类型赋值float64(float64, XXX)",它就可以正常工作.

If I remove the explict type assigment "float64(float64, XXX)" it works fine.

但是有没有什么我可以用 XXX 替换它来告诉它是我传递的类对象.

But is there something I can replace the XXX with to tell it is a class object I am passing.

推荐答案

如果你用 SOMETHING_3.class_type.instance_type 替换了 XXX,你给出的代码应该可以工作.

If you replaced XXX with SOMETHING_3.class_type.instance_type the code you've given should work.

值得注意的是,如果您尝试接收一组 jitclass 对象,这将变得更加棘手(我认为目前这是不可能的).如果您的完整问题/代码涉及这些 jitclass 对象的数组,我建议您考虑使用 NumPy 结构化数组而不是 jitclass.这主要是因为当前版本的 Numba 似乎不支持使用 jitclass 对象数组作为函数参数.这样做的原因是 jitclass 对象的数组将被解释为具有 numpy.object dtype 的 NumPy 数组,这在 Numba 的 nopython 模式中不受支持.由于它是 Numba 无法降低的类型(编译以在 nopython 模式下使用),因此 nopython 模式对于惰性编译(无函数签名)和急切编译(指定函数签名)都会失败.

It's worth noting that this becomes much more tricky (I believe it's currently impossible) to do if you're instead trying to take in an array of jitclass objects. If your full problem/code involves arrays of these jitclass objects, I would recommend you consider doing this with NumPy structured arrays rather than a jitclass. This is mainly because using an array of jitclass objects as a function parameter doesn't seem to to be supported in the current version of Numba. The reason for this is that an array of jitclass objects would be interpreted as a NumPy array with dtype of numpy.object, which is not a supported dtype in Numba's nopython mode. Since it's the type that Numba would be unable to lower (compile for use in nopython mode), nopython mode will fail for both lazy compilation (no function signature), and eager compilation (specifying function signature).

更新:

现在支持 jitclass 对象列表,但是在 Python 和 nopython 编译代码之间传递它们的开销非常大,所以请记住这一点.

Lists of jitclass objects are now supported, but there is very large overhead in passing them between Python and nopython compiled code, so keep that in mind.

这篇关于在 Numba 优化的 Python 中将类对象作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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