Kan
Kan

Reputation: 169

Parallel: Run for loop in Python

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!

Upvotes: 2

Views: 845

Answers (1)

Vor
Vor

Reputation: 35099

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()

Upvotes: 1

Related Questions