Parallel: Run for loop in Python
Question: I want to make my coed run in Parallel, which is shown as below,

    
    
    for j in range(nj):
        for i in range(ni):
            # assign matrix coefficient
    

This is a very large matrix, which results in very low execution time, how can
I run this kind of code in Parallel?

Thanks in advance!


Answer: You probably looking for `multiprocessing` module.

    
    
    import multiprocessing
    import random
    import time
    
    def f(x,y):
        print multiprocessing.current_process()
        time.sleep(random.random())
        return x*y
    
    p = multiprocessing.Pool(10)
    res= []
    for i in xrange(1,10):
      for j in xrange(1,10):
        res.append(p.apply_async(f, [i,j]))
    
    for r in res:
      print r.get()
    

