本篇内容主要讲解“怎么加速python脚本”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么加速python脚本”吧!
因为近期要写嵌套for循环,由于运算量有点大,耗时比较久。所以就在谷歌上搜了搜有没有办法可以提升python for loop的速度,然后就发现了非常好用的模块:Numba
Numba makes Python code fast
官方网址:http://numba.pydata.org/
# download from tsinghua mirror sitewget https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/Anaconda3-5.3.1-Linux-x86_64.sh# check the help messagebash Anaconda3-5.3.1-Linux-x86_64.sh -h# then install or install into Nonexistent Custom Directory by adding -pbash Anaconda3-5.3.1-Linux-x86_64.sh# add to the environmentecho ". /home/saber/anaconda3/etc/profile.d/conda.sh" >> ~/.bashrc
from numba import jit
import time
#define function A without numba
def func_A(a1,a2):
A_result=0
for i in range(a1,a2):
A_result+=i
return A_result
#define func A1 with numba
#just add the @jit
@jit
def func_A1(a1,a2):
A1_result=0
for i in range(a1,a2):
A1_result+=i
return A1_result
#record the elasped time
def time_func(func_A_i,*args):
start = time.time()
func_A_i(*args)
end = time.time()
print("Elasped time of func %s is %.4e"%(func_A_i.__name__,end-start))
time_func(func_A,1,10000000)
time_func(func_A,1,10000000)
print()
time_func(func_A1,1,10000000)
time_func(func_A1,1,10000000)
Elasped time of func func_A is 5.4757e-01
Elasped time of func func_A is 5.3267e-01
Elasped time of func func_A1 is 5.3686e-02
Elasped time of func func_A1 is 4.7684e-06
First, recall that Numba has to compile your function for the argument types given before it executes the machine code version of your function, this takes time. However, once the compilation has taken place Numba caches the machine code version of your function for the particular types of arguments presented. If it is called again the with same types, it can reuse the cached version instead of having to compile again.
到此,相信大家对“怎么加速python脚本”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。