Numba仅适用于typed个变量.它不仅需要check the types of all the items,还需要convert the whole list到输入列表中.这种隐式转换可能特别昂贵,因为CPython列出了,又名反射列表包含分配对象上的指针,并且每个对象都被引用计数.Numba的类型化列表是同质的,它们不包含引用,而是直接包含其中的值.这要高效得多,并且类似于具有NPS等附加功能的Numpyarray.
有没有办法告诉Numba按原样使用列表?
AFAIK,不.Numba代码中不再支持反射列表.对反射列表进行操作不仅效率低下,而且还会 destruct 类型系统.
最好的 Select 是create directly a typed list.下面是一个例子:
import numba as nb
# Quite fast part (less than 0.1 seconds)
reflected_lst = [i for i in range(2_000_000)]
# Slow part (3 seconds)
typed_lst = nb.typed.typedlist.List(reflected_lst)
# Very fast part (less than 2 µs) since `lst` is already a typed-list
test(typed_lst)
正如@roganjosh所提到的,请注意,列表生成包含在您的基准测试中,但这只占用执行时间的一小部分
请注意,Numba中的转换过程特别昂贵(与Numpy相反,请参阅下面的 comments ).有一个opened issue on this topic.引用开发商的话:
[...] we came to the conclusion that there is probably room for improvement.
[...] this problem is all down to implementation details.
到目前为止,该问题仍然悬而未决,并且有一个补丁可以稍微提高转换的性能,但速度仍然相当慢.