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倍

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: