问题描述
我试图了解@jitclass装饰器如何与嵌套类一起使用.我写了两个虚拟类:fifi和totofifi具有toto属性.这两个类都具有@jitclass装饰器,但是编译失败.这是代码:
I'm trying to understand how the @jitclass decorator works with nested classes. I have written two dummy classes: fifi and totofifi has a toto attribute. Both classes have the @jitclass decorator but compilation fails. Here's the code:
fifi.py
from numba import jitclass, float64
from toto import toto
spec = [('a',float64),('b',float64),('c',toto)]
@jitclass(spec)
class fifi(object):
def __init__(self, combis):
self.a = combis
self.b = 2
self.c = toto(combis)
def mySqrt(self,x):
s = x
for i in xrange(self.a):
s = (s + x/s) / 2.0
return s
toto.py:
from numba import jitclass,int32
spec = [('n',int32)]
@jitclass(spec)
class toto(object):
def __init__(self,n):
self.n = 42 + n
def work(self,y):
return y + self.n
启动代码的脚本:
from datetime import datetime
from fifi import fifi
from numba import jit
@jit(nopython = True)
def run(n,results):
for i in xrange(n):
q = fifi(200)
results[i+1] = q.mySqrt(i + 1)
if __name__ == '__main__':
n = int(1e6)
results = [0.0] * (n+1)
starttime = datetime.now()
run(n,results)
endtime = datetime.now()
print("Script running time: %s"%str(endtime-starttime))
print("Sqrt of 144 is %f"%results[145])
运行脚本时,我得到[...]
When I run the script, I get [...]
请注意,如果我删除了"fifi"中对"toto"的任何引用,则代码可以正常工作,并且由于使用了numba,我的速度提高了x16.
Note that if I remove any reference to 'toto' in 'fifi', the code works fine and I get a x16 speed up thanks to numba.
推荐答案
可以将jitclass用作另一个jitclass的成员,尽管这样做的方法没有得到很好的记录.您需要使用deferred_type
实例.这可以在Numba 0.27或更早的版本中使用.将fifi.py
更改为:
It is possible to use a jitclass as a member of another jitclass, although the way of doing this isn't well documented. You need to use a deferred_type
instance. This works in Numba 0.27 and possibly earlier. Change fifi.py
to:
from numba import jitclass, float64, deferred_type
from toto import toto
toto_type = deferred_type()
toto_type.define(toto.class_type.instance_type)
spec = [('a',float64),('b',float64),('c',toto_type)]
@jitclass(spec)
class fifi(object):
def __init__(self, combis):
self.a = combis
self.b = 2
self.c = toto(combis)
def mySqrt(self,x):
s = x
for i in xrange(self.a):
s = (s + x/s) / 2.0
return s
然后我得到输出:
$ python test.py
Script running time: 0:00:01.991600
Sqrt of 144 is 12.041595
可以在一些更高级的jitclass数据结构示例中看到此功能,例如:
This functionality can be seen in some of the more advanced jitclass examples of data structures, for example:
- stack.py
- linkedlist.py
- binarytree.py
这篇关于如何嵌套numba jitclass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!