Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/parallel/multiprocessing_sage.py
4056 views
1
"""
2
Parallel Iterator built using Python's multiprocessing module
3
"""
4
5
################################################################################
6
# Copyright (C) 2008 William Stein <[email protected]>
7
#
8
# Distributed under the terms of (any version of) the GNU
9
# General Public License (GPL). The full text of the GPL is available at:
10
#
11
# http://www.gnu.org/licenses/
12
################################################################################
13
14
from multiprocessing import Pool
15
from functools import partial
16
from sage.misc.fpickle import pickle_function, call_pickled_function
17
import ncpus
18
19
def pyprocessing(processes=0):
20
"""
21
Return a parallel iterator using a given number of processes
22
implemented using pyprocessing.
23
24
INPUTS:
25
26
- ``processes`` -- integer (default: 0); if 0, set to the number
27
of processors on the computer.
28
29
OUTPUT:
30
31
- a (partially evaluated) function
32
33
EXAMPLES::
34
35
sage: from sage.parallel.multiprocessing_sage import pyprocessing
36
sage: p_iter = pyprocessing(4)
37
sage: P = parallel(p_iter=p_iter)
38
sage: def f(x): return x+x
39
sage: v = list(P(f)(range(10))); v.sort(); v
40
[(((0,), {}), 0), (((1,), {}), 2), (((2,), {}), 4), (((3,), {}), 6), (((4,), {}), 8), (((5,), {}), 10), (((6,), {}), 12), (((7,), {}), 14), (((8,), {}), 16), (((9,), {}), 18)]
41
"""
42
if processes == 0: processes = ncpus.ncpus()
43
return partial(parallel_iter, processes)
44
45
def parallel_iter(processes, f, inputs):
46
"""
47
Return a parallel iterator.
48
49
INPUT:
50
51
- ``processes`` -- integer
52
- ``f`` -- function
53
- ``inputs`` -- an iterable of pairs (args, kwds)
54
55
OUTPUT:
56
57
- iterator over values of ``f`` at ``args,kwds`` in some random order.
58
59
EXAMPLES::
60
61
sage: def f(x): return x+x
62
sage: import sage.parallel.multiprocessing_sage
63
sage: v = list(sage.parallel.multiprocessing_sage.parallel_iter(2, f, [((2,), {}), ((3,),{})]))
64
sage: v.sort(); v
65
[(((2,), {}), 4), (((3,), {}), 6)]
66
"""
67
from twisted.internet import reactor # do not delete this (!) -- see trac 8785
68
69
if processes == 0: processes = ncpus.ncpus()
70
p = Pool(processes)
71
fp = pickle_function(f)
72
73
result = p.imap_unordered(call_pickled_function, [ (fp, t) for t in inputs ])
74
for res in result:
75
yield res
76
77
78