-
Memray -
Tracemalloc -
Memory_profiler
def sse_server(self):
def streamer():
while True:
try:
# do yield
...
except:
...
response = Response(streamer(), mimetype="text/event-stream")
response.headers["Cache-Control"] = "no-cache"
response.headers["X-Accel-Buffering"] = "no"
return response
def sse_server(self):
def streamer():
while True:
try:
# 生成事件数据
data = yield
# 这里可以添加生成数据的逻辑
except AllowException:
# 期待的,能继续生成数据的异常
continue
except GeneratorExit:
# 客户端连接关闭时退出生成器
break
except Exception as e:
# 其他异常处理
break
def generate():
for message in streamer():
if message:
yield f"data: {message}nn"
response = Response(generate(), mimetype="text/event-stream")
response.headers["Cache-Control"] = "no-cache"
response.headers["X-Accel-Buffering"] = "no"
return response
import tracemalloc
tracemalloc.start()
# ... 开始程序 ...
snapshot1 = tracemalloc.take_snapshot()
# ... 怀疑有泄漏的代码 ...
snapshot2 = tracemalloc.take_snapshot()
top_stats = snapshot2.compare_to(snapshot1, 'lineno')
for stat in top_stats[:10]:
print(stat)
analyzer_arm_rknn_4.py:397: size=3318 KiB (+18.6 MB), count=39426 (+10), average=501 K
def write_disk(self, force=False):
t = time.time()
if self.buffer["total_size"] == 0:
...
elif self.buffer["total_size"] > BUFFER_SIZE or t - self.buffer["t"] > BUFFER_INTERVAL or force:
...
self.buffer["t"] = t
self.buffer["total_size"] = 0
try:
f = open(self.save_path, "rb+")
for item in self.buffer["tasks"]:
item["call"](f, *item["args"])
f.close()
except Exception:
logger.debug(traceback.format_exc())
def reset_buffer(self, t):
self.buffer["t"] = t
self.buffer["total_size"] = 0
self.buffer["tasks"] = []
def write_disk(self, force=False):
t = time.time()
if self.buffer["total_size"] == 0:
...
elif self.buffer["total_size"] > BUFFER_SIZE or t - self.buffer["t"] > BUFFER_INTERVAL or force:
...
try:
f = open(self.save_path, "rb+")
for item in self.buffer["tasks"]:
item["call"](f, *item["args"])
f.close()
except Exception:
logger.debug(traceback.format_exc())
self.reset_buffer(t)
video_fetcher_2.py:273: size=20.4 MB (+496 kB), count=19082 (+2)
if self.record_task:
with self.record_task_mtx:
....
if self.record_task["now_sec"] == self.record_task["end_sec"] + 1:
# write disk
self.record_task = None
if self.record_task:
with self.record_task_mtx:
....
if self.record_task["now_sec"] >= self.record_task["end_sec"] + 1:
# write disk
self.record_task = None
-
Python 依赖的资源库没有释放内存 -
使用缓存时,确认过期后没有释放内存 -
缓存的过期条件有问题,没有触发 -
线程没有释放
-
没有 GC 的语言,一定要检查申请的资源是否有释放 -
使用线程或者进程时,尽量使用线程池或进程池 -
在使用缓存时,一定要检查缓存的过期条件 -
尽量监控资源指标,尽量在上线前发现问题
原文始发于微信公众号(内存泄漏):Python 也有内存泄漏?
免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论