【问题标题】:Coroutines in numbanumba 中的协程
【发布时间】:2017-06-10 02:32:33
【问题描述】:

我正在做一些需要快速协程的事情,我相信 numba 可以加快我的代码速度。

这是一个愚蠢的例子:一个函数将其输入平方,并加上它被调用的次数。

def make_square_plus_count():
    i = 0
    def square_plus_count(x):
        nonlocal i
        i += 1
        return x**2 + i
    return square_plus_count

你甚至不能 nopython=False JIT 这个,大概是因为 nonlocal 关键字。

但如果您使用类,则不需要nonlocal

def make_square_plus_count():
    @numba.jitclass({'i': numba.uint64})
    class State:
        def __init__(self):
            self.i = 0

    state = State()

    @numba.jit()
    def square_plus_count(x):
        state.i += 1
        return x**2 + state.i
    return square_plus_count

这至少有效,但如果你这样做nopython=True,它就会中断。

有没有可以用nopython=True 编译的解决方案?

【问题讨论】:

    标签: python coroutine numba


    【解决方案1】:

    如果你要使用状态类,你也可以使用方法而不是闭包(应该是非 python 编译的):

    import numba
    
    @numba.jitclass({'i': numba.uint64})
    class State(object):
        def __init__(self):
            self.i = 0
    
        def square_plus_count(self, x):
            self.i += 1
            return x**2 + self.i
    
    square_with_call_count = State().square_plus_count  # using the method
    print([square_with_call_count(i) for i in range(10)])
    # [1, 3, 7, 13, 21, 31, 43, 57, 73, 91]
    

    但是时间显示这实际上比纯 python 闭包实现要慢。我希望只要您不使用nonlocal numpy-arrays 或在您的方法(或闭包)中对数组进行操作,效率就会降低!

    【讨论】:

    • 我怎样才能inspect_types()你的State.square_plus_count
    • 我环顾四周,发现only ressource或多或少说这是不可能的。
    猜你喜欢
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多