如何从PHP获取MySQL查询的执行时间? [英] How to get the execution time of a MySQL query from PHP?

查看:471
本文介绍了如何从PHP获取MySQL查询的执行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从PHP执行MySQL查询,想知道它们的耗时.有什么方法可以从PHP获取MySQL查询的执行时间?

I execute MySQL queries from PHP and would like to know how time consuming they are. Is there any way to get the execution time of a MySQL query from PHP?

我还想知道执行时间是否取决于Web服务器的负载量.我可以想象,如果服务器忙于其他查询,则查询将花费更多时间来执行.另一方面,我可以想象,如果服务器繁忙,查询将仅等待轮到它,然后将被执行(没有并行执行的任何查询),并且等待时间不包括在执行时间中.那么,什么情况(在两种情况中)是正确的?

I also wonder if the execution time depends on how loaded is the web server. I can imagine that a query will take more time to execute if the server is busy with other queries. On the other hand, I can imagine that, if the server is busy, the query will just wait for its turn and then it will be executed (without any queries executed in parallel) and than the waiting time is not included into the execution time. So, what scenarios (out of two) is correct?

推荐答案

可能有一些方法可以通过MySQL进行,但是,简单(可靠)的方法是使用PHP的microtime函数,该函数返回当前时间.以毫秒为单位.

There is probably some way to do this via MySQL, however, the easy (and reliable) way is using PHP's microtime function, which returns the current time as milliseconds.

microtime()返回当前的Unix时间戳(以微秒为单位).此功能仅>在支持gettimeofday()系统调用的操作系统上可用.

microtime() returns the current Unix timestamp with microseconds. This function is only > available on operating systems that support the gettimeofday() system call.

getasfloat -在不带可选参数的情况下调用时,此函数返回字符串"msec sec",其中sec是自Unix纪元(0:00:00)以来的秒数.格林尼治标准时间1970年1月1日),毫秒是微秒部分.字符串的两个部分都以秒为单位返回.

getasfloat - When called without the optional argument, this function returns the string "msec sec" where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and msec is the microseconds part. Both portions of the string are returned in units of seconds.

如果可选的get_as_float设置为TRUE,则返回浮点数(以秒为单位).

If the optional get_as_float is set to TRUE then a float (in seconds) is returned.

一些示例代码:

$sql = '...';
$msc = microtime(true);
mysql_query($sql);
$msc = microtime(true)-$msc;
echo $msc . ' s'; // in seconds
echo ($msc * 1000) . ' ms'; // in millseconds

这篇关于如何从PHP获取MySQL查询的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆