Tracemalloc comes with python3 and does not need to be installed to analyze the memory usage of each line of code in the program.
For example, we can compare the memory usage after running some programs.
Import tracemalloc from copy import deepCopy tracemalloc.start() # run a line s=[[j for j in range(512)] for I in range(512)] T =[[j for j in range(1024)] for I in range(1024)] p= t.coopy () Dp = deepCopy (t) #print(t[:2]) #print(t[:2]) #print(t[:2] snapshot2.compare_to(snapshot1, 'lineno') for stat in top_stats: print(stat)Copy the code
The running results are as follows:
Ttr.py :10: size=29.8 MiB (+29.8 MiB), count=787460 (+787460), average=40 B D:\Anaconda3\lib\copy.py:215: size=8970 KiB (+8970 KiB), count=1027 (+1027), average=8944 B D:\Anaconda3\lib\copy.py:211: Size = 64.1kib (+ 64.1kib), count=1025 (+1025), average=64 bttr.py :11: size=8256 B (+8256 B), count=2 (+2), average=4128 B D:\Anaconda3\lib\copy.py:150: size=1376 B (+1376 B), count=3 (+3), average=459 B D:\Anaconda3\lib\tracemalloc.py:397: size=656 B (+656 B), count=5 (+5), average=131 B D:\Anaconda3\lib\tracemalloc.py:534: size=552 B (+552 B), count=3 (+3), average=184 B ttr.py:12: size=536 B (+536 B), count=1 (+1), average=536 B D:\Anaconda3\lib\copy.py:185: size=472 B (+472 B), count=1 (+1), average=472 B D:\Anaconda3\lib\copy.py:139: size=240 B (+240 B), count=2 (+2), average=120 B D:\Anaconda3\lib\copy.py:213: size=144 B (+144 B), count=2 (+2), average=72 B D:\Anaconda3\lib\tracemalloc.py:291: size=112 B (+112 B), count=2 (+2), average=56 B D:\Anaconda3\lib\copy.py:266: size=64 B (+64 B), count=1 (+1), average=64 B D:\Anaconda3\lib\tracemalloc.py:289: size=56 B (+56 B), count=1 (+1), average=56 B ttr.py:6: size=5710 KiB (+0 B), count=131578 (+0), average=44 B D:\Anaconda3\lib\tracemalloc.py:532: size=64 B (+0 B), count=1 (+0), average=64 BCopy the code
S =[[j for j in range(512)] for I in range(512)] T =[[j for j in range(1024)] for I in range(1024)] The memory usage is 29.8MiB, indicating a large difference. Careful analysis reveals that deepCopy () requires less memory than direct copy(). The main use of tracemalloc is to analyze the memory usage of a program and see which code uses a lot of memory and can be optimized.
And tracemalloc does not modify the original running code too much, it is very easy to use, in the future encounter memory analysis must remember tracemalloc this powerful library.