因为本人目前正在学习python,其中有一个叫numba的库,使用了llvm,我也不是很了解,但是看起来好像很牛B的样子,听说效率很高。所以我看了一些它的文档,按照官方提供的例子试了一遍:
pythonfrom numba import jit from numpy import arange from datetime import datetime # 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) start = datetime.now() print(sum2d(a)) stop = datetime.now() print(stop-start)
发现它平均需要花费53毫秒的时间,然后我将@jit注释掉,发现居然连1毫秒都不到,不是说numba效率很高吗?我想不出意外的话,肯定是我哪里弄错了,然后我试了好久,发现如果我把数组变得很大的话,numba的效率就体现了出来:
pythonfrom numba import jit from numpy import arange from datetime import datetime # 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(9999999).reshape(3333333,3) start = datetime.now() print(sum2d(a)) stop = datetime.now() print(stop-start)
不使用jit需要2.56秒的时间,而使用了jit才70毫秒,这已经不是同一个数量级了,但是对于一些简单的计算使用jit反而慢了呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
JIT是有代码预热的,同样的代码跑的次数多才能看出来优势的。
用了JIT速度真的是快了很多
比如之前我用opencv在Python上做二值化,一个3000*3000的图像,竟然需要十几秒,我当时就准备重归c++了,用了jit之后整个时间到了不到一秒
不知道jit原理是怎么样的