python - Numba 基本示例比纯 python 慢

标签 python optimization numba

我尝试使用基本示例来比较 numba 和纯 python,但得到了奇怪的结果。

这是 numba 示例:

from numba import jit
from numpy import arange
from time import time
# jit decorator tells Numba to compile this function.
# The argument types will be inferred by Numba when function is called.
@jit
def sum2d(arr):
    M, N = arr.shape
    result = 0.0
    for i in range(M):
        for j in range(N):
            result += arr[i,j]
    return result

a = arange(9).reshape(3,3)
t = time()
print(sum2d(a))
print time() - t

这是我用 numba 得到的时间 0.0469660758972 秒

如果没有 numba,我会得到更快的结果 9.60826873779e-05 秒

最佳答案

需要根据参数的类型编译函数,您可以在定义函数时通过提供签名( eager compilation )来执行此操作,也可以在第一次调用函数时让 numba 为您推断类型(毕竟它被称为即时 [JIT] 编译:-))。

您尚未指定任何签名,因此它会在您第一次调用该函数时推断并编译该函数。他们even state that在您使用的示例中:

# jit decorator tells Numba to compile this function.
# The argument types will be inferred by Numba when function is called.

但是后续运行(具有相同类型和数据类型)将会很快:

t = time()
print(sum2d(a))    # 0.035051584243774414
print(time() - t)

%timeit sum2d(a)   # 1000000 loops, best of 3: 1.57 µs per loop

最后一个命令使用了IPython %timeit command .

关于python - Numba 基本示例比纯 python 慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42164886/

相关文章:

python - scipy 中的线性插值

python - Numba - 字符串类型

python numba : how to slice a column from a numpy array?

python Pandas : trying to vectorize a function using date_range

python - 如何在 Ubuntu 中运行 Anaconda 提示符

python - 具有不同 X 轴顺序的 Pandas groupby 图

python - pip install 生成错误 : Command errored out with exit status 1

php - 遍历 PHP 数组是否比遍历 MySQLi 关联数组更好?

php - 将 php 作为 css/js : Is it fast enough? 有什么缺点?

list - 一种生成给定长度组合的更快方法,保留顺序