PHP获取MySQL执行SQL语句查询时间的方法
具体实现方式如下所示:
//计时开始
runtime();
//执行查询
mysql_query($sql);
//计时结束.
echo runtime(1);
//计时函数
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语句的执行耗时进行分析有助于:
1. 判断SQL语句的编写是否合理且高效;
2. 检查数据库字段及表结构设计是否合理。
方法一:在系统底层对SQL操作类进行改造,通常类的调用结构为:
业务Model -> DB类 -> 执行SQL
可根据实际情况选择特定阶段进行改造,例如修改DB类;常见的修改逻辑如下:
public function execute($sql) {
//code...
/*检测sql执行时间,超过执行时间记录到日志中*/
$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){ //修改时间范围,单位:秒
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执行时间的方式如下:
// garvin: Measure query time.
// TODO-Item http://sourceforge.net/tracker/index.php?func=detail&aid=571934&group_id=23067&atid=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功能。
该方法更适合用于统计多条SQL的执行状况。
曾见过某博客在访问页面后提示共查询数据库几次及总耗时,开启MySQL Profile即可轻松实现此类功能。
批注1:关于microtime函数
计算微秒的函数microtime()可返回当前UNIX时间戳和微秒数,返回值为浮点数,单位为秒。该函数仅在支持gettimeofday()系统调用的操作系统下可用,建议查阅手册了解详情。使用时需注意可能引发不明错误。
批注2:Profile最多保存100条记录,该如何解决?
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.
最大记录数限制为100条,无法直接更改。
引用2:PHP获取毫秒级时间戳的方法
Java中可通过getTime()获取。若需与Java程序进行高精度毫秒级对接通信,则需使用PHP输出毫秒级时间。为获取更精准的毫秒级时间戳,可使用以下代码:
<?php
function getMillisecond() {
list($t1, $t2) = explode(' ', microtime());
return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
}
echo getMillisecond();
运行结果示例:1.46647658229E+12
以上即为PHP获取MySQL执行SQL语句查询时间方法的完整内容,希望能提供参考,感谢支持。