zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

获取php页面执行时间,数据库读写次数,函数调用次数等(THINKphp)

PHP数据库执行 获取 时间 页面 读写 thinkphp
2023-06-13 09:15:00 时间
THINKphp里面有调试运行状态的效果:

Process:0.2463s(Load:0.0003sInit:0.0010sExec:0.1095sTemplate:0.1355s)|DB:13queries0writes|Cache:2gets,0writes|UseMem:415kb|LoadFile:20|CallFun:63,1370

代表的含义:

运行信息:整体执行时间0.2463s(加载:0.0003s初始化:0.0010s执行:0.1095s模板:0.1355s)|数据库:13次读操作0次写操作|缓存:2次读取,0次写入|使用内存:415kb|加载文件:20|函数调用:63(自定义),1370(内置)

下面来分析一下这些数据是怎么获取到的?

PHP获取页面执行时间:
复制代码代码如下:

/**
*得到当前时间
*/
functiongetMicrotime(){

list($usec,$sec)=explode("",microtime());
return((float)$usec+(float)$sec);
}


使用:上面的方法可以获取当前时间,计算页面执行时间可以在程序开头和结尾出分别执行该方法,最后时间差就是页面执行的时间,原理很简单。

获取数据库读写次数

在数据库插入和读取的时候设置一个全局变量,每次执行成功一次$i++一次,,这是tp里面db类的方法,而N的方法是:自动累计的一个方法。

同理缓存也是这样计算出来的

内存的开销
memory_get_usage可以获取当前内存的消耗量,可以在程序开始和结尾分别调用,差值就是内存的开销

加载文件的数量
get_included_files:Getsthenamesofallfilesthathavebeenincludedusinginclude,include_once,requireorrequire_once.

也就是可以获取到所有的include,require的文件数,返回引入文件的数组:

官网例子":

复制代码代码如下:

<?php
//Thisfileisabc.php

include"test1.php";
include_once"test2.php";
require"test3.php";
require_once"test4.php";

$included_files=get_included_files();

foreach($included_filesas$filename){
echo"$filenamen";
}
?>


返回的结果是:

abc.php
test1.php
test2.php
test3.php
test4.php

函数调用方法
第一个看这个,感觉是在每个方法里面调用时自动+1.但是感觉不大可能,貌似这个每个方法里写不靠谱,这群里讨论半天,最后发现php的一个函数:

get_defined_functions返回引入PHP文件的所有方法的array格式,包括自定义的,内置的。

引入官网的一个例子:

复制代码代码如下:
<?php
functionmyrow($id,$data)
{
return"<tr><th>$id</th><td>$data</td></tr>n";
}
$arr=get_defined_functions();
print_r($arr);
?>


结果是:

复制代码代码如下:
Array
(
[internal]=>Array
(
[0]=>zend_version
[1]=>func_num_args
[2]=>func_get_arg
[3]=>func_get_args
[4]=>strlen
[5]=>strcmp
[6]=>strncmp
...
[750]=>bcscale
[751]=>bccomp
)

[user]=>Array
(
[0]=>myrow
)
)


user为自定义方法,internal为内置方法数组。

引申:

get_defined_constants获取定义所有常量的数组
get_defined_functions获取定义所有函数的数组
get_defined_vars获取定义所有变量的数组
get_declared_classes返回已经定义的类的数组