简体   繁体   中英

How to parallelize a for loop in Python?

Some posts about parallelizing for loop in Python already exist such as this one but I can't use them to deal with my issue. Let's take a simple example. I have three lists :

L1 = [1,2,3]
L2 = [3,4,5]
L3 = [5,6,7]

I would like to double each element of the list. I could do this :

for l in [L1,L2,L3] :
    for i in range(len(l)) :
        l[i] = l[i]*2

How please could I parallelize this code to transform L1, L2 and L3 in parallel ?

Note that this example is just to have a clear and easy to understand example, I know that it is not a good idea in reality to parallelize a quick code like that

Using Asyncio:

import asyncio
import time
def background(f):
    def wrapped(*args, **kwargs):
        return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)

    return wrapped

@background
def your_function(argument):
    time.sleep(2)
    print('function finished for '+str(argument))


for i in range(10):
    your_function(i)


print('loop finished')

Using multiprocessing:

from multiprocessing import Pool

L1 = [1,2,3]
L2 = [3,4,5]
L3 = [5,6,7]

def f(li):
    return [x * 2 for x in li]

if __name__ == '__main__':
    with Pool(4) as pool:
        print(pool.map(f, [L1, L2, L3]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM