内存泄露排查 笔记

排查内存泄露过程

示例代码

  • 主函数 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"}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值