【python】—— 使用經驗:並行計算代替for循環

在python中,for循環是執行串行計算,換句話說,for循環中的每個階段一定要在上一個階段完成之後才能被執行。當循環的代數特別多時,這樣會非常耗費時間。

map( ) 這個函數能夠將for循環的串行計算改變成並行計算。

import time

def func(x):
    x = (x**2)**2
    return x

lists = list(range(100000))

start = time.time()
a=[]
for num in lists:
    a.append(func(num))
end = time.time()
print('Serial computing time:\t',end - start)

start = time.time()
b = map(func,lists)
end = time.time()
print('Parallel Computing time:\t',end - start)

print(a == list(b))
【結果】
Serial computing time:	 0.11100649833679199
Parallel Computing time:	 0.0
True

延伸閱讀:python並行計算
多線程並行計算map

發佈了103 篇原創文章 · 獲贊 33 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章