结论:performance_schema 通过 events_waits_history 表的 wait_class 和 wait_type 字段,可拆分出 Buffer Pool IO(wait_class=wait/io/file/...)、锁等待(wait_class=wait/lock/...)、CPU(wait_class=wait/.../cpu)。偏差源于事件采样丢失和统计粒度不足,推荐结合 pt-query-digest 的 digest_text + perfmon 的 CPU/IO 混合分析。
【拆分方法】
- Buffer Pool IO:过滤 wait_class=wait/io/file/... 且 wait_type 包含 'buffer_pool' 的事件,计算总耗时
- 锁等待:wait_class=wait/lock/... 且 wait_type 包含 'spinlock'/'mutex' 的事件
- CPU:wait_class=wait/.../cpu 的事件(需开启 detailed_wait_class)
【偏差原因】
- events_waits_history 是固定大小的环形缓冲区,高频查询会丢失尾部数据
- 事件合并统计导致 30% 误差(如多个等待事件被归并为单个统计项)
- Buffer Pool 等待包含 flush_list 和 page_cleaner 等非查询相关等待
【工具推荐】
- pt-query-digest 的 digest_text 字段包含估算的 CPU/IO/锁耗时
- perfmon 模板监控 CPU/IO/锁等待(需开启 perf_event_paranoid=-1)
- 通过 SHOW ENGINE INNODB STATUS 的 'BUFFER POOL AND MEMORY' 分析物理读耗时
- 使用 MySQL 8.0 的 performance_schema 的 waits_by_host_by_event_name 视图
【实践建议】
-
在 /etc/my.cnf 中增加: performance_schema = ON performance_schema_events_waits_history_size = 10000 performance_schema_events_waits_history_long_size = 100000
-
用 pt-query-digest 分析慢查询: pt-query-digest --user=root --password=xxx --host=127.0.0.1 --port=3306 --slowquery=10000 --limit=100 --create-slowlog=1 --print --output=json /path/to/slow.log
-
通过 perfmon 监控: perf stat -e cpu-clock,page-faults,context-switches,cycles,instructions,cache-references,cache-misses -r 10 -- sleep 10
-
查看 Buffer Pool 等待: SHOW ENGINE INNODB STATUS\G
-
用 MySQL 官方工具分析: mysqlcheck --analyze --auto-repair --all-databases
【踩坑案例】 曾遇到某金融系统因未开启 detailed_wait_class,导致锁等待被归并为 'wait/lock/table/...',实际是行锁和表锁混用造成统计偏差。开启后通过 wait_type 区分,发现 70% 的等待来自行锁 contention。