在Python中的并行处理

什么是一个简单的代码,并行处理在Python 2.7中? 我在网上find的所有例子都是错综复杂的,包括不必要的代码。

我将如何做一个简单的蛮力整数因子程序,我可以在每个核心(4)因子1整数? 我真正的程序可能只需要2个核心,并且需要共享信息。

我知道parallel-python和其他库存在,但我想保持使用的库的数量最less,因此我想使用thread和/或多multiprocessing库,因为他们来与python

在python中开始并行处理的一个很好的简单方法就是多处理中的池映射 – 就像通常的python映射一样,但是单独的函数调用分布在不同数量的进程上。

保理就是一个很好的例子 – 你可以通过暴力检查所有可用任务的分工:

 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 

这给了我

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

mincemeat是我find的最简单的映射/减less实现。 另外,它对依赖关系非常轻 – 这是一个单一的文件,并与标准库一切。

我同意,如果您想要保留在标准库中,使用Pool from multiprocessing可能是最好的途径。 如果你有兴趣做其他types的并行处理,但不学习任何新东西(即仍然使用与multiprocessing相同的接口),那么你可以尝试使用pathos ,它提供了几种forms的并行映射,并且具有与multiprocessing确实。

 Python 2.7.6 (default, Nov 12 2013, 13:26:39) [GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import numpy >>> numToFactor = 976 >>> def isFactor(x): ... result = None ... div = (numToFactor / x) ... if div*x == numToFactor: ... result = (x,div) ... return result ... >>> from pathos.multiprocessing import ProcessingPool as MPool >>> p = MPool(4) >>> possible = range(1,int(numpy.floor(numpy.sqrt(numToFactor)))+1) >>> # standard blocking map >>> result = [x for x in p.map(isFactor, possible) if x is not None] >>> print result [(1, 976), (2, 488), (4, 244), (8, 122), (16, 61)] >>> >>> # asynchronous map (there's also iterative maps too) >>> obj = p.amap(isFactor, possible) >>> obj <processing.pool.MapResult object at 0x108efc450> >>> print [x for x in obj.get() if x is not None] [(1, 976), (2, 488), (4, 244), (8, 122), (16, 61)] >>> >>> # there's also parallel-python maps (blocking, iterative, and async) >>> from pathos.pp import ParallelPythonPool as PPool >>> q = PPool(4) >>> result = [x for x in q.map(isFactor, possible) if x is not None] >>> print result [(1, 976), (2, 488), (4, 244), (8, 122), (16, 61)] 

另外, pathos有一个叫做pyina的姊妹软件包,它运行mpi4py ,但提供了在MPI中运行的并行映射,可以使用多个调度器运行。

另外一个好处是, pathos带有比标准python好得多的序列化程序,所以它比序列化函数和其他东西的multiprocessingfunction要好得多。 你可以做任何事情从翻译。

 >>> class Foo(object): ... b = 1 ... def factory(self, a): ... def _square(x): ... return a*x**2 + self.b ... return _square ... >>> f = Foo() >>> fb = 100 >>> g = f.factory(-1) >>> p.map(g, range(10)) [100, 99, 96, 91, 84, 75, 64, 51, 36, 19] >>> 

获取代码在这里: https : //github.com/uqfoundation