sys.monitoring是python 3.12引入的低开销监控api,通过事件开关、作用域控制和c层优化显著降低性能影响,但非零开销;需按需启用事件、合理分配instrument id并避免回调中触发监控。

sys.monitoring 是什么,它真能低开销吗?
sys.monitoring 是 Python 3.12 引入的正式监控 API,目标是替代已弃用的 sys.settrace 和 sys.setprofile,提供更细粒度、更低开销的运行时事件捕获能力。它不是“零开销”,但通过事件开关(event enable/disable)、精确作用域(per-thread、per-code-object)和 C 层直通机制,把性能影响压到远低于传统 trace 的水平——前提是你不盲目开启所有事件。
常见错误现象:一上来就调用 sys.monitoring.set_events(0, sys.monitoring.ALL_EVENTS),结果函数调用变慢 3–5 倍,误以为“低开销”是宣传话术。
- 只在需要监控的代码段前后动态启用/禁用事件,例如用上下文管理器包装关键函数
- 优先使用粒度最粗、开销最小的事件,如
sys.monitoring.events.LINE或sys.monitoring.events.CALL,避免默认启用sys.monitoring.events.INSTRUCTION - 每个事件监听器必须注册到具体 instrument_id(整数 ID),且同一 ID 不能重复注册;ID 超出
sys.monitoring.MAX_INSTRUMENTS(当前为 16)会直接报ValueError
如何注册一个只监听函数调用的监控器?
核心是三步:分配 instrument ID → 注册回调 → 启用事件。注意回调函数签名固定为 callback(code: types.CodeType, line: int, opcode: int, arg: int) -> None,Python 3.12 不接受带额外参数的闭包或方法。
使用场景:你想统计某个模块里所有用户定义函数的调用次数,又不想污染源码或拖慢整个进程。
import sys
import types
<h1>1. 分配 ID(必须是 0–15 的整数)</h1><p>INSTR_ID = 1</p><h1>2. 定义回调:只关心 CALL 事件,忽略其他</h1><p>def call_handler(code: types.CodeType, line: int, opcode: int, arg: int) -> None:
if opcode == sys.monitoring.events.CALL:
print(f"→ {code.co_name} called at line {line}")</p><h1>3. 注册并启用(仅对特定 code object 生效)</h1><p>sys.monitoring.register(INSTR_ID, call_handler)
sys.monitoring.use_tool(INSTR_ID, "my_profiler") # 可选,用于调试识别
sys.monitoring.set_events(INSTR_ID, sys.monitoring.events.CALL)</p>
容易踩的坑:
调用 Cutout.Pro 视觉处理 API 进行背景移除、人像抠图和照片增强,支持文件上传与图片 URL 输入。
- 回调中不能调用可能触发监控的代码(比如
print()本身可能触发CALL,造成递归或死锁);生产环境建议用无锁队列或原子计数器 -
set_events()对全局所有 code object 生效,若只想监控某几个函数,需配合sys.monitoring.set_local_events()+code.co_monitoring标记(需手动 patch code object)
为什么 set_local_events 不生效?检查 co_monitoring 标志
sys.monitoring.set_local_events() 只对设置了 co_monitoring 属性的 code object 生效。这个属性默认为 None,Python 不会自动为你标记——你得自己改。
常见错误现象:调用了 set_local_events(id, events),但回调从不触发。
- 必须在函数编译后、执行前设置
code.co_monitoring = True,例如通过装饰器或 import hook 修改<strong>code</strong> -
co_monitoring是只读属性,只能在 code object 创建时通过types.CodeType()构造,或用ctypes强制写入(不推荐) - 更稳妥的做法:用
sys.monitoring.set_events()全局启用,再在回调里用code.co_filename和code.co_name过滤目标函数
性能影响提示:局部启用比全局启用省电,但每次函数入口仍要查 co_monitoring 标志位,开销约 1–2ns;而全局启用后所有函数都进监控路径,开销取决于事件类型(CALL 约 5ns,INSTRUCTION 可达 50ns+)。
监控数据怎么导出?别依赖 print,用原子变量或 mmap
sys.monitoring 回调运行在解释器主循环内,阻塞式 I/O(如 print()、logging.info())会显著放大延迟,甚至导致线程卡顿。
可给出简短示例(计数场景):
import sys
import threading
<p>_call_counts = {}
_count_lock = threading.Lock()</p><p>def safe_count_handler(code: types.CodeType, line: int, opcode: int, arg: int) -> None:
if opcode != sys.monitoring.events.CALL:
return
key = (code.co_filename, code.co_name)
with _count_lock:
_call_counts[key] = _call_counts.get(key, 0) + 1</p><p>sys.monitoring.register(2, safe_count_handler)
sys.monitoring.set_events(2, sys.monitoring.events.CALL)</p>
容易被忽略的地方:
回调函数里不能做任何可能引发 GC、GIL 释放或信号处理的操作;如果需要高频采集(比如每毫秒采样),应改用 mmap 共享内存 + ring buffer,由外部进程异步读取——sys.monitoring 本身不提供缓冲或序列化能力,它只是个轻量钩子。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










