如何分析 Python 中的内存使用情况?
分析 Python 中的内存使用情况
Python 3.4引入了tracemalloc模块来深入分析内存分配。要显示特定函数的内存分配统计信息:
from tracemalloc import start, take_snapshot, display_top start() # Code to profile memory usage snapshot = take_snapshot() display_top(snapshot)
随时间监控内存
要跟踪一段时间内的内存使用情况:
from collections import Counter import time def count_prefixes(): counts = Counter() with open('/usr/share/dict/american-english') as words: words = list(words) for word in words: counts[word[:3]] += 1 time.sleep(0.0001) return counts.most_common(3) count_prefixes() snapshot = take_snapshot() display_top(snapshot)
使用单独的线程监控
在主线程运行时监控单独线程的内存使用情况:
from queue import Queue from threading import Thread def memory_monitor(queue): while True: try: command = queue.get(timeout=0.1) if command == 'stop': return snapshot = take_snapshot() print(datetime.now(), 'max RSS', getrusage(RUSAGE_SELF).ru_maxrss) except Empty: continue queue = Queue() monitor_thread = Thread(target=memory_monitor, args=(queue,)) monitor_thread.start() try: count_prefixes() finally: queue.put('stop') monitor_thread.join()
以上是如何有效地分析和监控 Python 中的内存使用情况?的详细内容。更多信息请关注PHP中文网其他相关文章!