Last active
August 29, 2021 04:28
-
-
Save geniusnhu/5321bd3fe0a4a8914759661ebc8da21d to your computer and use it in GitHub Desktop.
Example of using tracemalloc in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> import tracemalloc | |
>>> import numpy as np | |
>>> def create_array(x, y): | |
>>> x = x**2 | |
>>> y = y**3 | |
>>> return np.ones((x, y, 1024, 3), dtype=np.uint8) | |
>>> tracemalloc.start() | |
>>> ### Run application | |
>>> arr = create_array(30,10) | |
>>> ### take memory usage snapshot | |
>>> snapshot = tracemalloc.take_snapshot() | |
>>> top_stats = snapshot.statistics('lineno') | |
>>> ### Print top 10 files allocating the most memory | |
>>> print("[ Top 10 ]") | |
>>> for stat in top_stats[:10]: | |
>>> print(stat) | |
[ Top 10 ] | |
/usr/local/lib/python3.7/dist-packages/numpy/core/numeric.py:192: size=2637 MiB, count=2, average=1318 MiB | |
/usr/lib/python3.7/threading.py:289: size=216 B, count=6, average=36 B | |
/usr/lib/python3.7/codeop.py:141: size=189 B, count=2, average=94 B | |
/usr/local/lib/python3.7/dist-packages/debugpy/_vendored/pydevd/pydevd.py:1532: size=144 B, count=2, average=72 B | |
/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py:2820: size=112 B, count=3, average=37 B | |
/usr/lib/python3.7/queue.py:182: size=80 B, count=1, average=80 B | |
/usr/lib/python3.7/queue.py:107: size=80 B, count=1, average=80 B | |
/usr/lib/python3.7/threading.py:1264: size=72 B, count=1, average=72 B | |
## ================================================================================== | |
##### Explanation ##### | |
## count: Number of memory blocks (int) | |
## size: Total size of memory blocks in bytes (int) | |
## traceback: Traceback where the memory block was allocated, Traceback instance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment