如下所示:
//計(jì)時(shí)開(kāi)始
runtime();
//執(zhí)行查詢(xún)
mysql_query($sql);
//計(jì)時(shí)結(jié)束.
echo runtime(1);
//計(jì)時(shí)函數(shù)
function runtime($mode=0) {
static $t;
if(!$mode) {
$t = microtime();
return;
}
$t1 = microtime();
list($m0,$s0) = explode(" ",$t);
list($m1,$s1) = explode(" ",$t1);
return sprintf("%.3f ms",($s1+$m1-$s0-$m0)*1000);
}
對(duì)sql的執(zhí)行時(shí)間進(jìn)行分析可以:
1,確定sql的書(shū)寫(xiě)是否合理,高效
2,檢查字段、表的設(shè)計(jì)是否合理
方法1:在系統(tǒng)底層對(duì)sql操作類(lèi)進(jìn)行改寫(xiě),通常類(lèi)的結(jié)構(gòu)是
業(yè)務(wù)model ---》 db類(lèi) ---》 執(zhí)行sql
可以根據(jù)情況在某階段進(jìn)行改寫(xiě),比如db類(lèi);通常會(huì)修改
public function execute($sql) {
//code...
/*檢測(cè)sql執(zhí)行時(shí)間,超過(guò)執(zhí)行時(shí)間記錄到日志中*/
$start_time = array_sum(explode(' ', microtime()));
$this->lastresult = mysql_query($sql,$this->link) or $this->displayerror($sql);
$end_time = array_sum(explode(' ', microtime()));
$differ = $end_time - $start_time;
if($differ >0.001){ //修改時(shí)間范圍,單位:秒
putContent('sqlLOG', date('Y-m-d H:i:s', $start_time)." "
. date('Y-m-d H:i:s', $end_time)." "
.$differ. " ".$sql."\r\n");
}
//code...
}
引用:
phpmyadmin中的代碼,獲得query執(zhí)行時(shí)間如下:
// garvin: Measure query time.
// TODO-Item http://sourceforge.net/tracker/index.php?func=detailaid=571934group_id=23067atid=377411
$querytime_before = array_sum(explode(' ', microtime()));
$result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
$querytime_after = array_sum(explode(' ', microtime()));
$GLOBALS['querytime'] = $querytime_after - $querytime_before;
除了這種方式還可以使用mysql的profile。
這個(gè)更適合統(tǒng)計(jì)多條sql的執(zhí)行情況。
我見(jiàn)過(guò)好像是一個(gè)博客,訪問(wèn)頁(yè)面之后會(huì)有一個(gè)提示大概說(shuō)共查詢(xún)了幾次數(shù)據(jù)庫(kù),用了多長(zhǎng)時(shí)間查詢(xún)數(shù)據(jù),那么開(kāi)啟mysql的profile就可以輕松實(shí)現(xiàn)了。
批注1:micortime函數(shù)
計(jì)算微秒的函數(shù)micortime(),可以返回當(dāng)前UNIX時(shí)間戳和微秒數(shù)。返回浮點(diǎn)數(shù)單位為秒。不過(guò)函數(shù)僅在支持gettimeofday()系統(tǒng)調(diào)用的操作系統(tǒng)下可用??梢圆橄率謨?cè)詳細(xì)了解下??赡芤l(fā)有些不明的錯(cuò)誤,注意。
批注2:profile最多保存100條記錄,這個(gè)要怎么解決呢?
profiling_history_size
The number of statements for which to maintain profiling information if profiling is enabled. The default value is 15. The maximum value is 100. Setting the value to 0 effectively disables profiling.
這個(gè)最大就100條了,改不了。
引用2:PHP獲取毫秒級(jí)時(shí)間戳的方法
java里面可以通過(guò)gettime();獲取。如果是要與java寫(xiě)的某些程序進(jìn)行高精度的毫秒級(jí)的對(duì)接通信,則需要使用PHP輸出毫秒級(jí)的時(shí)間。為獲取更為精準(zhǔn)的毫秒級(jí)時(shí)間戳可以使用下面的代碼:
?php
function getMillisecond() {
list($t1, $t2) = explode(' ', microtime());
return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
}
echo getMillisecond();
運(yùn)行結(jié)果:1.46647658229E+12
以上這篇PHP獲取MySQL執(zhí)行sql語(yǔ)句的查詢(xún)時(shí)間方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- MySQL執(zhí)行update語(yǔ)句和原數(shù)據(jù)相同會(huì)再次執(zhí)行嗎
- 一條SQL語(yǔ)句在MySQL中是如何執(zhí)行的