Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
multiprocessing example
  • Loading branch information
bbengfort committed Jul 15, 2016
commit 0d956a1df6d1ebc5353e6ac0f54265028a27b59d
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@ MANIFEST
*.egg-info
*.pyc
*~

# Ignore mprof generated files
mprofile_*.dat
55 changes: 55 additions & 0 deletions examples/multiprocessing_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""
An undecorated example of a script that allocates memory in multiprocessing
workers to demonstrate the use of memory_profiler with multiple processes.

Run this script with mprof run -C python multiprocessing_example.py
You can then visualize the usage with mprof plot.
"""

import time
import multiprocessing as mp

# Big numbers
X6 = 10 ** 6
X7 = 10 ** 7


def worker(num, wait, amt=X6):
"""
A function that allocates memory over time.
"""
frame = []

for idx in range(num):
frame.extend([1] * amt)
time.sleep(wait)

del frame


def main_sequential():
"""
A sequential version of the work, where one worker is called at a time.
"""
worker(5, 5, X6)
worker(5, 2, X7)
worker(5, 5, X6)
worker(5, 2, X7)


def main_multiproc():
"""
A multiprocessing version of the work, where workers work in their own
child processes and are collected by the master process.
"""
pool = mp.Pool(processes=4)
tasks = [
pool.apply_async(worker, args) for args in
[(5, 5, X6), (5, 2, X7), (5, 5, X6), (5, 2, X7)]
]

results = [p.get() for p in tasks]


if __name__ == '__main__':
main_multiproc()