Parallel Processing in python

前端 未结 4 2000
南方客
南方客 2020-11-28 04:29

Whats a simple code that does parallel processing in python 2.7? All the examples Ive found online are convoluted and include unnecessary codes.

how would i do a sim

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 05:09

    A good simple way to start with parallel processing in python is just the pool mapping in mutiprocessing -- its like the usual python maps but individual function calls are spread out over the different number of processes.

    Factoring is a nice example of this - you can brute-force check all the divisions spreading out over all available tasks:

    from multiprocessing import Pool
    import numpy
    
    numToFactor = 976
    
    def isFactor(x):
        result = None
        div = (numToFactor / x)
        if div*x == numToFactor:
            result = (x,div)
        return result
    
    if __name__ == '__main__':
        pool = Pool(processes=4)
        possibleFactors = range(1,int(numpy.floor(numpy.sqrt(numToFactor)))+1)
        print 'Checking ', possibleFactors
        result = pool.map(isFactor, possibleFactors)
        cleaned = [x for x in result if not x is None]
        print 'Factors are', cleaned
    

    This gives me

    Checking  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
    Factors are [(1, 976), (2, 488), (4, 244), (8, 122), (16, 61)]
    

提交回复
热议问题