日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python向量化與for循環耗時對比分析_python

作者:Nani_xiao ? 更新時間: 2022-07-15 編程語言

向量化與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倍

原文鏈接:https://blog.csdn.net/xiao_lxl/article/details/78134537

欄目分類
最近更新