排查内存泄露过程
示例代码
-
主函数 main.py
from fastapi import FastAPI from .memory_debug import debugger app = FastAPI(title="Memory Leak Demo") _cache = [] def process_data(data): """模拟内存泄漏:将处理后的数据存入全局列表""" processed = { 'id': data['id'], 'value': data['value'], # 故意放大数据 'timestamp': data['timestamp'] } _cache.append(processed) # 内存泄漏点(持续累积) return processed @app.get("/process-data") async def leaky_endpoint(size: int = 1000): """生成测试数据集""" dataset = [{ 'id': i, 'value': str(i) * 10, # 故意创建较大字符串,导致内存膨胀 'timestamp': i } for i in range(size)] # 在处理数据前拍摄内存快照,标记为 "before_processing" debugger.take_snapshot("before_processing") results = [] for data in dataset: results.append(process_data(data)) # 处理完成后再次拍摄内存快照,标记为 "after_processing" debugger.take_snapshot("after_processing") print("length _cache : ", len(_cache)) return { "processed": len(results), "message": f"Processed { size} items (with memory leak)" } @app.get("/debug/memory") async def debug_memory(compare: str = None, limit: int = 5): """内存调试端点""" if compare: snap1, snap2 = compare.split(",") return { "comparison": debugger.compare_snapshots(snap1, snap2, limit) } else: return { "current": debugger.get_memory_stats() } @app.get("/clear-cache") async def clear_cache(): """清空泄漏缓存""" _cache.clear() print("length _cache : ", len(_cache)) return { "message": "Cache cleared"}

最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



