1. 程式人生 > >Mysql使用profiling分析慢sql語句的原因

Mysql使用profiling分析慢sql語句的原因

         CleverCode的同事最近給我推薦了一個分析mysql中sql語句的工具profiling,發現這個工具非常不錯,能夠很準確的分析出查詢的過程中sql語句具體的時間花在了哪裡。CleverCode在這裡總結一下,分享給大家。


1 簡介    

    MySQL 的 Query Profiler 是一個使用非常方便的 Query 診斷分析工具,通過該工具可以獲取一條Query 在整個執行過程中多種資源的消耗情況,如 CPU,IO,IPC,SWAP 等,以及發生的 PAGE FAULTS,CONTEXT SWITCHE 等等,同時還能得到該 Query 執行過程中 MySQL 所呼叫的各個函式在原始檔中的位置。
    
    MySQL5.0.37版本以上支援PROFILING除錯功能,讓您可以瞭解SQL語句消耗資源的詳細資訊。因為它需要呼叫系統的getrusage()函式,所以只是在Linux/Unix類平臺上才能使用,而不能在Windows平臺上使用。而且,PROFILING是針對處理程序(process)而不是執行緒(thread)的,伺服器上的其他應用,可能會影響您的除錯結果,因此,這個工具適合開發過程中的除錯,如果要在生產環境中除錯使用,則要注意它的侷限性。


2 操作

2.1 檢視是否已經啟用profile,預設是關閉的。
mysql> select @@profiling;
+-------------+
| @@profiling |
+-------------+
|           0 | 
+-------------+
1 row in set (0.00 sec)


2.2 啟用profiling。變數profiling是使用者變數,每次都得重新啟用。
mysql> set profiling = 1;  
Query OK, 0 rows affected (0.00 sec)


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


2.3 執行以下語句。為避免之前已經把 SQL 存放在 QCACHE 中, 建議在執行 SQL 時, 強制 SELECT 語句不進行 QCACHE 檢測。這樣可以提交分析的準確性。

mysql> use db_user;
mysql> select sql_no_cache count(*) from system_user;
mysql> update system_user set username = 'CleverCode' where id = 10;
mysql> select sql_no_cache count(*) from system_user where age > 20;
...... 

2.4 使用show profile查詢最近一條語句的執行資訊。(分析:select sql_no_cache count(*) from system_user where age > 20)
mysql> show profile;


2.5 使用show profiles。檢視在伺服器上執行語句的列表。(查詢id,花費時間,語句) 。

mysql> show profiles; 



2.6 使用show profile查詢制定ID的執行資訊。這裡分析ID為6的語句。(分析:select sql_no_cache count(*) from system_user where age > 20)。

mysql> show profile for query 6;


2.7 獲取 CPU 和 Block IO 的消耗。

mysql>  show profile block io,cpu for query 6;


mysql> show profile all for query 6;
mysql> show profile cpu,block io,memory,swaps,context switches,source for query 6;


ALL displays all information

BLOCK IO displays counts for block input and output operations

CONTEXT SWITCHES displays counts for voluntary and involuntary context switches

CPU displays user and system CPU usage times

IPC displays counts for messages sent and received

MEMORY is not currently implemented

PAGE FAULTS displays counts for major and minor page faults

SOURCE displays the names of functions from the source code, together with the name and line number of the file in which the function occurs


SWAPS displays swap counts

1)原創作品,出自"CleverCode的部落格",請勿轉載,否則追究版權法律責任。