1. 程式人生 > >Python 巧妙的實現並行

Python 巧妙的實現並行

star art ssi image inf body 分時 img com

需求

  給定一個list 針對list 中每個元素執行一定的操作(這個操作很費時間,例如爬數據的時候調用某個網站的接口),返回操作後的list

  例如 給定 1-10個數,在每個數字後面加個字母a

方法

1、利用線程池pool 及map 函數 實現

 1 from multiprocessing import Pool
 2 from multiprocessing.dummy import Pool as ThreadPool
 3 import time
 4 pool = ThreadPool(10)
 5 
 6 #定義函數
 7 def add(x):
 8     time.sleep(0.2)
9 return str(x) + a 10 11 ll = list(range(0,10)) 12 13 14 #原始map 15 start = time.time() 16 res = map(add, ll) 17 print res 18 print time.time() - start 19 20 #線程池map 21 start = time.time() 22 res = pool.map(add,ll) 23 print res 24 print time.time() - start

技術分享圖片

結論:

可以發現 運行時間縮短了。一定要保證所執行的函數比較費時間,才可以用,否則 大部分時間都用在分發任務上了,

多線程不一定比單線程快。 感興趣的同學可以試試把time.sleep()去掉。

參考:

http://python.jobbole.com/81690/

Python 巧妙的實現並行