意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

Python中向量化与for循环的耗时是怎样,哪个有优势

来源:恒创科技 编辑:恒创科技编辑部
2023-12-30 22:25:59
这篇文章主要介绍“Python中向量化与for循环的耗时是怎样,哪个有优势”,有一些人在Python中向量化与for循环的耗时是怎样,哪个有优势的问题上存在疑惑,接下来小编就给大家来介绍一下相关的内容,希望对大家解答有帮助,有这个方面学习需要的朋友就继续往下看吧。


   

 


Python中向量化与for循环的耗时是怎样,哪个有优势

向量化与for循环耗时对比

深度学习中,可采用向量化替代for循环,优化耗时问题

对比例程如下,参考Andrew NG的课程笔记

import time
import numpy as np
a = np.random.rand(1000000)
b = np.random.rand(1000000)

tic = time.time()
c = np.dot(a,b)
toc = time.time()
print(c)
print("Vectorized version: " , str(1000*(toc-tic)) + "ms")

c = 0
tic1 = time.time()
for i in range(1000000):
    c += a[i]*b[i]
toc1 = time.time()
print(c)
print("For loop version: " , str(1000*(toc1-tic1)) + "ms")

处理百万数据,耗时相差400多倍。

效果图:

向量化数据的相比于for循环的优势

例子

import numpy as np
import time
a = np.random.rand(1000000)
b = np.random.rand(1000000)
tic = time.time()

c = np.dot(a,b)
toc = time.time()
print©
print(“vectorized version:” + str((toc-tic))+“s”)

c1 = 0
tic = time.time()
for i in range(1000000):
c1 += a[i]*b[i]
toc = time.time()
print(c1)
print(“Nonvectorized version:” + str(toc-tic)+“s”)

结果

250487.97870397285
vectorized version:0.002000093460083008s
250487.9787039739
Nonvectorized version:0.957054615020752s

可以看出向量化后执行时间比使用for循环快478倍


以上就是关于“Python中向量化与for循环的耗时是怎样,哪个有优势”的介绍了,感谢各位的阅读,如果大家想要了解更多相关的内容,欢迎关注恒创科技,小编每天都会为大家更新不同的知识。
上一篇: 如何用Python来破解压缩包,操作是什么 下一篇: Python并行加速怎样实现,方法是什么