如下所示:
//計(jì)時(shí)開始 runtime(); //執(zhí)行查詢 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); }
對sql的執(zhí)行時(shí)間進(jìn)行分析可以:
1,確定sql的書寫是否合理,高效
2,檢查字段、表的設(shè)計(jì)是否合理
方法1:在系統(tǒng)底層對sql操作類進(jìn)行改寫,通常類的結(jié)構(gòu)是
業(yè)務(wù)model ---》 db類 ---》 執(zhí)行sql
可以根據(jù)情況在某階段進(jìn)行改寫,比如db類;通常會(huì)修改
public function execute($sql) { //code... /*檢測sql執(zhí)行時(shí)間,超過執(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í)行情況。
我見過好像是一個(gè)博客,訪問頁面之后會(huì)有一個(gè)提示大概說共查詢了幾次數(shù)據(jù)庫,用了多長時(shí)間查詢數(shù)據(jù),那么開啟mysql的profile就可以輕松實(shí)現(xiàn)了。
批注1:micortime函數(shù)
計(jì)算微秒的函數(shù)micortime(),可以返回當(dāng)前UNIX時(shí)間戳和微秒數(shù)。返回浮點(diǎn)數(shù)單位為秒。不過函數(shù)僅在支持gettimeofday()系統(tǒng)調(diào)用的操作系統(tǒng)下可用??梢圆橄率謨栽敿?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獲取毫秒級時(shí)間戳的方法
java里面可以通過gettime();獲取。如果是要與java寫的某些程序進(jìn)行高精度的毫秒級的對接通信,則需要使用PHP輸出毫秒級的時(shí)間。為獲取更為精準(zhǔn)的毫秒級時(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語句的查詢時(shí)間方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
標(biāo)簽:鄂州 綏化 崇左 太原 白銀 衡陽 辛集 廊坊
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP獲取MySQL執(zhí)行sql語句的查詢時(shí)間方法》,本文關(guān)鍵詞 PHP,獲取,MySQL,執(zhí)行,sql,語句,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。