如何在类的成员函数上使用numba? [英] How do I use numba on a member function of a class?

查看:344
本文介绍了如何在类的成员函数上使用numba?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用稳定版的Numba 0.30.1.

I'm using the stable version of Numba 0.30.1.

我可以这样做:

import numba as nb
@nb.jit("void(f8[:])",nopython=True)                             
def complicated(x):                                  
    for a in x:
        b = a**2.+a**3.

作为测试用例,并且加速是巨大的.但是,如果我需要加快类中的函数的速度,我不知道如何继续.

as a test case, and the speedup is enormous. But I don't know how to proceed if I need to speed up a function inside a class.

import numba as nb
def myClass(object):
    def __init__(self):
        self.k = 1
    #@nb.jit(???,nopython=True)                             
    def complicated(self,x):                                  
        for a in x:
            b = a**2.+a**3.+self.k

我为self对象使用哪种数字类型?我需要在类中包含此函数,因为它需要访问成员变量.

What numba type do I use for the self object? I need to have this function inside a class since it needs to access a member variable.

推荐答案

我处在非常相似的情况下,我找到了一种在类内部使用Numba-JITed函数的方法.

I was in a very similar situation and I found a way to use a Numba-JITed function inside of a class.

诀窍是使用静态方法,因为这种方法不会被称为将对象实例添加到参数列表之前.无法访问self的缺点是您不能使用在方法外部定义的变量.因此,您必须将它们从有权访问self的调用方法传递给静态方法.就我而言,我不需要定义包装方法.我只需要将要JIT编译的方法分成两个方法即可.

The trick is to use a static method, since this kind of methods are not called prepending the object instance to the argument list. The downside of not having access to self is that you cannot use variables defined outside of the method. So you have to pass them to the static method from a calling method that has access to self. In my case I did not need to define a wrapper method. I just had to split the method I wanted to JIT compile into two methods.

在您的示例中,解决方案是:

In the case of your example, the solution would be:

from numba import jit

class MyClass:
    def __init__(self):
        self.k = 1

    def calculation(self):
        k = self.k
        return self.complicated([1,2,3],k)

    @staticmethod
    @jit(nopython=True)                             
    def complicated(x,k):                                  
        for a in x:
            b = a**2 .+ a**3 .+ k

这篇关于如何在类的成员函数上使用numba?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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