इस कोड को समानांतर करने का सबसे आसान तरीका क्या है?
मुझे वास्तव में यह पसंद concurrent.futures
है, 3.2 संस्करण के बाद से Python3 में उपलब्ध है - और PyPi पर 2.6 और 2.7 के लिए बैकपोर्ट के माध्यम से ।
आप थ्रेड्स या प्रक्रियाओं का उपयोग कर सकते हैं और सटीक उसी इंटरफ़ेस का उपयोग कर सकते हैं।
बहु
इसे किसी फ़ाइल में डालें - futuretest.py:
import concurrent.futures
import time, random # add some random sleep time
offset = 2 # you don't supply these so
def calc_stuff(parameter=None): # these are examples.
sleep_time = random.choice([0, 1, 2, 3, 4, 5])
time.sleep(sleep_time)
return parameter / 2, sleep_time, parameter * parameter
def procedure(j): # just factoring out the
parameter = j * offset # procedure
# call the calculation
return calc_stuff(parameter=parameter)
def main():
output1 = list()
output2 = list()
output3 = list()
start = time.time() # let's see how long this takes
# we can swap out ProcessPoolExecutor for ThreadPoolExecutor
with concurrent.futures.ProcessPoolExecutor() as executor:
for out1, out2, out3 in executor.map(procedure, range(0, 10)):
# put results into correct output list
output1.append(out1)
output2.append(out2)
output3.append(out3)
finish = time.time()
# these kinds of format strings are only available on Python 3.6:
# time to upgrade!
print(f'original inputs: {repr(output1)}')
print(f'total time to execute {sum(output2)} = sum({repr(output2)})')
print(f'time saved by parallelizing: {sum(output2) - (finish-start)}')
print(f'returned in order given: {repr(output3)}')
if __name__ == '__main__':
main()
और यहाँ उत्पादन है:
$ python3 -m futuretest
original inputs: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
total time to execute 33 = sum([0, 3, 3, 4, 3, 5, 1, 5, 5, 4])
time saved by parallellizing: 27.68999981880188
returned in order given: [0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
बहु सूत्रण
अब बदलने ProcessPoolExecutor
के लिए ThreadPoolExecutor
, और मॉड्यूल को फिर से चलाने:
$ python3 -m futuretest
original inputs: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
total time to execute 19 = sum([0, 2, 3, 5, 2, 0, 0, 3, 3, 1])
time saved by parallellizing: 13.992000102996826
returned in order given: [0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
अब आपने मल्टीथ्रेडिंग और मल्टीप्रोसेसिंग दोनों किया है!
प्रदर्शन और दोनों का एक साथ उपयोग करने पर ध्यान दें।
परिणामों की तुलना करने के लिए नमूनाकरण बहुत छोटा है।
हालांकि, मुझे संदेह है कि मल्टीथ्रेडिंग सामान्य रूप से विंडोज पर मल्टीप्रोसेसिंग की तुलना में अधिक तेज होगी, क्योंकि विंडोज फोर्किंग का समर्थन नहीं करता है इसलिए प्रत्येक नई प्रक्रिया को लॉन्च होने में समय लगता है। लिनक्स या मैक पर वे शायद करीब होंगे।
आप कई प्रक्रियाओं के अंदर कई थ्रेड्स को घोंसला बना सकते हैं, लेकिन कई प्रक्रियाओं को बंद करने के लिए कई थ्रेड्स का उपयोग नहीं करने की सिफारिश की जाती है।
calc_stuff
?