新网创想网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
本篇内容主要讲解“怎么加速python脚本”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么加速python脚本”吧!
通海网站制作公司哪家好,找成都创新互联公司!从网页设计、网站建设、微信开发、APP开发、响应式网站开发等网站项目制作,到程序开发,运营维护。成都创新互联公司自2013年创立以来到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选成都创新互联公司。
因为近期要写嵌套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脚本”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!