-
Notifications
You must be signed in to change notification settings - Fork 25
/
multiprocessing.html
133 lines (127 loc) · 5.43 KB
/
multiprocessing.html
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
<!DOCTYPE html>
<html>
<script type="text/javascript">var blog_title = "How to do Multiprocessing in Python";</script>
<script type="text/javascript">var publication_date = "December 21, 2019";</script>
<head>
<link rel="icon" href="images/ml_logo.png">
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<base target="_blank">
<script type="text/javascript" src="javascripts/blog_head.js"></script>
</head>
<body>
<script type="text/javascript" src="javascripts/blog_header.js"></script>
<!-- MAIN CONTENT -->
<div id="main_content_wrap" class="outer">
<section id="main_content" class="inner">
<p>
If you spend a lot of time waiting around for your code to run,
and you've tried
<a href="https://e2eml.school/code_optimization.html">
all the easier things</a>, you can sometimes get
a big speedup by parallelizing it — breaking it into
chunks and running each chunk separately. Laptops typically
typically have at least two cores, and many have four.
Desktop boxes can have as many as 32. But Python is single-threaded.
By default it will only run on one core at a time.
<a href="https://docs.python.org/3/library/multiprocessing.html">
The <code>multiprocessing</code> package</a> helps us to use as
many cores as we want.
</p>
<p>
Here's a minimal example that you can copy and paste to get
started with.
</p>
<pre><code>from multiprocessing import Pool
import os
import numpy as np
def f(n):
return np.var(np.random.sample((n, n)))
result_objs = []
n = 1000
with Pool(processes=os.cpu_count() - 1) as pool:
for _ in range(n):
result = pool.apply_async(f, (n,))
result_objs.append(result)
results = [result.get() for result in result_objs]
print(len(results), np.mean(results), np.var(results))
</code></pre>
(<a href="https://gitlab.com/snippets/1924217">
Here's the snippet on GitLab.</a>)
<ul>
<li>
<p>
<code>f(n)</code> is a function with a burdensome calculation.
</p>
</li>
<li>
<p>
<a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool">
<code>Pool</code></a> is a collection of worker processes.
</p>
</li>
<li>
<p>
When initializing a <code>Pool</code>,
the <code>processes</code> keyword argument
chooses how many workers to create. It doesn't make sense
to create more workers than you have processors.
<code>os.cpu_count()</code> tells you exactly how many that is.
If you leave one
processor free you can still run Firefox and listen to Spotify
while your code runs.
</p>
</li>
<li>
<p>
<code>Pool.apply_async()</code> assigns a job to your worker
pool, but doesn't wait around for the result. Instead it returns
a placeholder. We can use the placeholder to get the actual
result by calling <code>result_placeholder.get()</code>.
</p>
</li>
<li>
<p>
<code>Pool.apply_async()</code> takes a function as a first
argument and a tuple of arguments for that function
as a second argument. Because we want each worker to
run <code>f(n)</code>, we pass <code>apply_async(f, (n,))</code>.
</p>
</li>
<li>
<p>
If you were to immediately call <code>get()</code> on the
result placeholder from <code>apply_async()</code>,
it would hold up the for loop while it waited for the result.
In parallelization terminology, it blocks all the other
workers from getting new jobs. In this case, you would still
have several workers, but they would each take turns doing one
job while the others stood around and waited. Better to
collect all the result placeholders and gather up the
results when the works have done their jobs.
</p>
</li>
</ul>
<p>
The <code>multiprocessing</code> package is incredibly powerful.
This is only the tiniest part of its capabilities. But hopefully
it's a part that you'll find particularly useful.
</p>
<script type="text/javascript" src="javascripts/blog_signature.js"></script>
</section>
</div>
<script type="text/javascript" src="javascripts/blog_footer.js"></script>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-10180621-3");
pageTracker._trackPageview();
} catch(err) {}
</script>
</body>
</html>