向量化与for循环耗时对比——python实现

时间:2022-12-31 20:28:17

向量化与for循环耗时对比——python实现

深度学习中,可采用向量化替代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循环耗时对比——python实现