numba函数何时编译? [英] When does a numba function compile?

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

问题描述

我正在研究这个示例:

http://numba.pydata.org/numba-doc/0.15.1/examples.html#multi-threading

并指出:

此时应确保inner_func已编译,因为编译必须在主线程上进行.在此示例中就是这种情况,因为我们使用了jit().

You should make sure inner_func is compiled at this point, because the compilation must happen on the main thread. This is the case in this example because we use jit().

在该示例中,在函数上调用jit似乎可以确保当时的编译.

It seems in the example that calling jit on a function ensures compilation at that time.

如果不是在我们将jit与参数类型指定为修饰符的函数上调用jit的情况下,多线程示例是否可以工作?我认为这等同于询问如果用装饰器将其绑定,是否可以在定义时编译该函数.

Would the multithreaded example work if instead of calling jit on the function we had used jit with argument types specified as a decorator? I think this is equivalent to asking if the function would be compiled upon definition if jitted with a decorator.

import numba as nb
import numpy as np
def inner_func(result, a, b):
    threadstate = savethread()
    for i in range(len(result)):
        result[i] = np.exp(2.1 * a[i] + 3.2 * b[i])
    restorethread(threadstate)
signature = nb.void(nb.double[:], nb.double[:], nb.double[:])
inner_func_nb = nb.jit(signature, nopython=True)(inner_func)

vs

import numba as nb
import numpy as np
signature = nb.void(nb.double[:], nb.double[:], nb.double[:])
@nb.jit(signature, nopython=True)
def inner_func(result, a, b):
    threadstate = savethread()
    for i in range(len(result)):
        result[i] = np.exp(2.1 * a[i] + 3.2 * b[i])
    restorethread(threadstate)

推荐答案

除非我丢失了某些内容,否则您的两个示例是完全等效的,不是因为numba所做的任何事情(或没有做任何事情),而是因为装饰器就是这样做的工作.我将解释一般原理,您可以仔细检查这是否是您要询问的转换.这段代码:

Unless I'm missing something, your two examples are exactly equivalent, not because of anything numba does (or doesn't do), but because that's how decorators work. I'll explain the general principle and you can double-check whether that's the transformation you are asking about. This code:

@d(arg)
def f(x): ...

在定义上等同于:

_decorator = d(arg)
def f(x): ...
f = _decorator(f)

如果我们合理地假设d(arg)没有副作用,可以将其重写为:

which, if we make the reasonable assumptions that d(arg) has no side effects, can be rewritten as:

def f(x): ...
f = d(arg)(f)

装饰者甚至无法分辨出差异(没有故意使用易碎的黑魔法).

The decorator can't even tell the difference (without deliberately using fragile black magic).

唯一的区别是,在第一个示例中,您调用了修饰的函数inner_func_nb而不是用它代替inner_func.如果您调用inner_func,这将导致不同的行为,因为在第一个示例中,您将调用未装饰的,未绑定的函数.这并不意味着不会发生拼合,只是其结果以不同的名称存储.

The sole difference is that, in the first example, you called the decorated function inner_func_nb instead of replacing inner_func with it. This would cause different behavior if you called inner_func, since in the first example you'd be calling the un-decorated un-jitted function. That doesn't mean the jitting doesn't happen, only that its result is stored under a different name.

这篇关于numba函数何时编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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