Python 3.4 bao gồm một module mới: tracemalloc
. Nó cung cấp số liệu thống kê chi tiết về mã nào được cấp phát bộ nhớ nhiều nhất. Dưới đây là một ví dụ hiển thị ba dòng đầu phân bổ bộ nhớ.
from collections import Counter
import linecache
import os
import tracemalloc
def display_top(snapshot, key_type='lineno', limit=3):
snapshot = snapshot.filter_traces((
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<unknown>"),
))
top_stats = snapshot.statistics(key_type)
print("Top %s lines" % limit)
for index, stat in enumerate(top_stats[:limit], 1):
frame = stat.traceback[0]
# replace "/path/to/module/file.py" with "module/file.py"
filename = os.sep.join(frame.filename.split(os.sep)[-2:])
print("#%s: %s:%s: %.1f KiB"
% (index, filename, frame.lineno, stat.size/1024))
line = linecache.getline(frame.filename, frame.lineno).strip()
if line:
print(' %s' % line)
other = top_stats[limit:]
if other:
size = sum(stat.size for stat in other)
print("%s other: %.1f KiB" % (len(other), size/1024))
total = sum(stat.size for stat in top_stats)
print("Total allocated size: %.1f KiB" % (total/1024))
tracemalloc.start()
counts = Counter()
fname = '/usr/share/dict/american-english'
with open(fname) as words:
words = list(words)
for word in words:
prefix = word[:3]
counts[prefix] += 1
print('Top prefixes:', counts.most_common(3))
snapshot = tracemalloc.take_snapshot()
display_top(snapshot)
Và đây là kết quả:
Top prefixes: [('con', 1220), ('dis', 1002), ('pro', 809)]
Top 3 lines
#1: scratches/memory_test.py:37: 6527.1 KiB
words = list(words)
#2: scratches/memory_test.py:39: 247.7 KiB
prefix = word[:3]
#3: scratches/memory_test.py:40: 193.0 KiB
counts[prefix] += 1
4 other: 4.3 KiB
Total allocated size: 6972.1 KiB
Nguồn
2017-08-14 16:31:27
tài liệu cá bảy màu chính thức là một chút minimial; để xem các tài nguyên khác, hãy xem [ví dụ này] (http://smira.ru/wp-content/uploads/2011/08/heapy.html) và [bài viết heapy] (http://guppy-pe.sourceforge.net/ heapy-thesis.pdf). – tutuDajuju