python引入jit_python numba jit效率如何提高

本文通过实验对比了Python中使用Numba库的JIT编译前后对不同规模数组处理速度的影响,揭示了JIT编译对于大规模计算任务的优势。
部署运行你感兴趣的模型镜像

因为本人目前正在学习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反而慢了呢?

JIT是有代码预热的,同样的代码跑的次数多才能看出来优势的。

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd18981.html

相关文章 Recommend

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值