使用DECO就像在Python編程中查找或者創(chuàng)建兩個(gè)函數(shù)一樣簡(jiǎn)便烁兰。第一個(gè)函數(shù)是我們想要并行運(yùn)行的函數(shù)疾掰,該函數(shù)使用@concurrent修飾一忱。第二個(gè)函數(shù)調(diào)用使用@concurrent修飾的函數(shù)共缕,并且使用@synchronized修飾自己洗出。修飾第二個(gè)函數(shù)是可選的,但是卻提供了非惩脊龋酷的益處翩活。讓我們看個(gè)例子:
@concurrent?#?We?add?this?for?the?concurrent?function
def?process_lat_lon(lat,?lon,?data):
? ? #Does?some?work?which?takes?a?while
? ? return?result
@synchronized?#?And?we?add?this?for?the?function?which?calls?the?concurrent?function
def?process_data_set(data):
? ? results?=?defaultdict(dict)
? ? for?lat?in?range(...):
? ? ? ? for?lon?in?range(...):
? ? ? ? ? ? results[lat][lon]?=?process_lat_lon(lat,?lon,?data)
? ? return?results
這就是要做的事情,我們只需要改動(dòng)兩行代碼就能使程序并行化蜓萄。此刻隅茎,程序?qū)⒊浞掷盟跈C(jī)器上所有CPU核,這使得程序飛速運(yùn)行嫉沽。
局限
@concurrent修飾器僅僅是加速運(yùn)行時(shí)間多于約1ms的那些函數(shù)
如果函數(shù)運(yùn)行時(shí)間少于1ms辟犀,你的代碼反而會(huì)運(yùn)行的更慢
@synchronized修飾器僅僅能在“簡(jiǎn)單”函數(shù)上起作用,確信你的函數(shù)滿足下面的標(biāo)準(zhǔn):
僅是調(diào)用或者賦值@concurrent函數(shù)的結(jié)果到索引的對(duì)象绸硕,就像下面的形式:
concurrent(...)
result[key] = concurrent(…)
不要間接的讀取被@concurrent函數(shù)調(diào)用而賦值的對(duì)象