python向量化與for循環(huán)耗時對比分析
向量化與for循環(huán)耗時對比
深度學(xué)習(xí)中,可采用向量化替代for循環(huán),優(yōu)化耗時問題
對比例程如下,參考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")處理百萬數(shù)據(jù),耗時相差400多倍。
效果圖:

向量化數(shù)據(jù)的相比于for循環(huán)的優(yōu)勢

例子
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”)
結(jié)果
250487.97870397285
vectorized version:0.002000093460083008s
250487.9787039739
Nonvectorized version:0.957054615020752s
可以看出向量化后執(zhí)行時間比使用for循環(huán)快478倍
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python計算三角函數(shù)之a(chǎn)sin()方法的使用
這篇文章主要介紹了Python計算三角函數(shù)之a(chǎn)sin()方法的使用,是Python入門的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05
Python實現(xiàn)統(tǒng)計給定字符串中重復(fù)模式最高子串功能示例
這篇文章主要介紹了Python實現(xiàn)統(tǒng)計給定字符串中重復(fù)模式最高子串功能,涉及Python針對字符串的遍歷、排序、切片、運算等相關(guān)操作技巧,需要的朋友可以參考下2018-05-05
python學(xué)生管理系統(tǒng)代碼實現(xiàn)
這篇文章主要為大家詳細(xì)介紹了python學(xué)生管理系統(tǒng)代碼實現(xiàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03
PyTorch模型轉(zhuǎn)換為ONNX格式實現(xiàn)過程詳解
這篇文章主要為大家介紹了PyTorch模型轉(zhuǎn)換為ONNX格式實現(xiàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
Python捕獲全局的KeyboardInterrupt異常的方法實現(xiàn)
KeyboardInterrupt異常是Python中的一個標(biāo)準(zhǔn)異常,它通常發(fā)生在用戶通過鍵盤中斷了一個正在運行的程序,本文主要介紹了Python捕獲全局的KeyboardInterrupt異常的方法實現(xiàn),感興趣的可以了解一下2024-08-08

