Parfor for Python

前端 未结 8 1374
死守一世寂寞
死守一世寂寞 2020-12-07 17:46

I am looking for a definitive answer to MATLAB\'s parfor for Python (Scipy, Numpy).

Is there a solution similar to parfor? If not, what is the complication for creat

8条回答
  •  借酒劲吻你
    2020-12-07 18:10

    Jupyter Notebook

    To see an example consider you want to write the equivalence of this Matlab code on in Python

    matlabpool open 4
    parfor n=0:9
       for i=1:10000
           for j=1:10000
               s=j*i   
           end
       end
       n
    end
    disp('done')
    

    The way one may write this in python particularly in jupyter notebook. You have to create a function in the working directory (I called it FunForParFor.py) which has the following

    def func(n):
        for i in range(10000):
            for j in range(10000):
                s=j*i
        print(n)
    

    Then I go to my Jupyter notebook and write the following code

    import multiprocessing  
    import FunForParFor
    
    if __name__ == '__main__':
        pool = multiprocessing.Pool(processes=4)
        pool.map(FunForParFor.func, range(10))
        pool.close()
        pool.join()   
        print('done')
    

    This has worked for me! I just wanted to share it here to give you a particular example.

提交回复
热议问题