Skip to content

Instantly share code, notes, and snippets.

@marksnoopy
Last active October 19, 2015 02:43
Show Gist options
  • Save marksnoopy/b38a7d43af57dce558b7 to your computer and use it in GitHub Desktop.
Save marksnoopy/b38a7d43af57dce558b7 to your computer and use it in GitHub Desktop.
辅助开发人员分析和优化SQL的那些工具

Analytics

tip: 因为平时大家用的最多的就是 explain ,所以这里我就把 explain 放在最后来分享,使得大家能够留意到除了 explain 以外的其他好工具。

1. mysql profile

(1). 目的

检查 SQL 的资源消耗情况

(2). 配置

mysql 中 profile 的相关配置一共有三个

mysql> show variables like '%profiling%';
+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| have_profiling         | YES   | 
| profiling              | OFF   | 
| profiling_history_size | 15    | 
+------------------------+-------+
3 rows in set (0.00 sec)

其中 having_profiling 这个配置在 mysql 5.1.x 的版本中是没有的,在 5.5.x + 以后增加,每个选项的相关含义如下:

配置 说明
having_profiling 当前版本的 mysql 是否支持 profile. 如果支持,则为 YES; 反之则为 NO. 这个值为只读,不能通过 set 命令进行赋值.
profiling 当前会话中 profile 是否打开. 如果已经打开, 则为 ON, 反之, 则为 OFF. 该值默认为 ON. 可以通过 set profiling = 1 或者 set profiling = ON 打开 profile, set profiling = 0 或者 set profiling = OFF 关闭 profile.
profiling_history_size 记录 profile 的条数, 默认是15条. 最大值是100(即时设置的值 > 100 ,也会默认记录为 100). 如果该值设为0, 则 profile 不会记录任何查询,相当于 profiling 设置为 OFF. profile 采取的是“出栈入栈”的形式,即在记录的查询数达到 profiling_history_size 时,则把最老的记录踢出 profile 栈,最新的记录入栈.

这里介绍一个小技巧, mysql 命令行中可以通过 select @@变量名 直接获取变量的值, 例如:

mysql> select @@profiling;   
+-------------+
| @@profiling |
+-------------+
|           1 | 
+-------------+
1 row in set, 1 warning (0.00 sec)

(3). SQL 执行的资源消耗

纬度 项目
BLOCK IO IO 资源消耗
CONTEXT SWITCHES 上下文切换资源消耗
CPU CPU 资源消耗
IPC 数据收发资源消耗
MEMORY 内存资源消耗
PAGE FAULTS [页面错误情况](http://blog.csdn.net/wujiandao/article/details/7632547)
SOURCE
SWAPS 交换次数

(4). SQL 执行每个阶段的时间消耗

阶段 消耗

参考

https://dev.mysql.com/doc/refman/5.1/en/show-profile.html

2、mysql explain

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment