Why is passing a list (of length n) to a numba nopython function an O(n) operation

微笑、不失礼 提交于 2019-12-10 11:35:18

问题


This is only a question to satisfy my curiosity I'm not actually planning on using lists as arguments for a numba function.

But I was wondering why passing a list to a numba function seems like an O(n) operation, while it's an O(1) operation in pure-Python functions.

Some simple example code:

import numba as nb

@nb.njit
def take_list(lst):
    return None

take_list([1, 2, 3])  # warmup

And the timings:

for size in [10, 100, 1000, 10000, 100000, 1000000]:

    lst = [0]*size
    print(len(lst))
    %timeit take_list(lst)   # IPythons "magic" timeit

Results:

10
4.06 µs ± 26.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
100
14 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
1000
109 µs ± 434 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
10000
1.08 ms ± 17.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
100000
10.7 ms ± 26.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
1000000
112 ms ± 383 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

回答1:


Manipulating a Python list takes Python API calls, which are forbidden in nopython mode. Numba actually copies the list contents into its own data structure, which takes time proportional to the size of the list.



来源:https://stackoverflow.com/questions/44489126/why-is-passing-a-list-of-length-n-to-a-numba-nopython-function-an-on-operati

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!