Skip to content

Commit 0d956a1

Browse files
committed
multiprocessing example
1 parent aa8b30c commit 0d956a1

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,6 @@ MANIFEST
55
*.egg-info
66
*.pyc
77
*~
8+
9+
# Ignore mprof generated files
10+
mprofile_*.dat
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
An undecorated example of a script that allocates memory in multiprocessing
3+
workers to demonstrate the use of memory_profiler with multiple processes.
4+
5+
Run this script with mprof run -C python multiprocessing_example.py
6+
You can then visualize the usage with mprof plot.
7+
"""
8+
9+
import time
10+
import multiprocessing as mp
11+
12+
# Big numbers
13+
X6 = 10 ** 6
14+
X7 = 10 ** 7
15+
16+
17+
def worker(num, wait, amt=X6):
18+
"""
19+
A function that allocates memory over time.
20+
"""
21+
frame = []
22+
23+
for idx in range(num):
24+
frame.extend([1] * amt)
25+
time.sleep(wait)
26+
27+
del frame
28+
29+
30+
def main_sequential():
31+
"""
32+
A sequential version of the work, where one worker is called at a time.
33+
"""
34+
worker(5, 5, X6)
35+
worker(5, 2, X7)
36+
worker(5, 5, X6)
37+
worker(5, 2, X7)
38+
39+
40+
def main_multiproc():
41+
"""
42+
A multiprocessing version of the work, where workers work in their own
43+
child processes and are collected by the master process.
44+
"""
45+
pool = mp.Pool(processes=4)
46+
tasks = [
47+
pool.apply_async(worker, args) for args in
48+
[(5, 5, X6), (5, 2, X7), (5, 5, X6), (5, 2, X7)]
49+
]
50+
51+
results = [p.get() for p in tasks]
52+
53+
54+
if __name__ == '__main__':
55+
main_multiproc()

0 commit comments

Comments
 (0)