你有(至少)两种解决方案:
相当“幼稚”的方法是在一段代码之前和之后使用 microtime(true) 来获取其执行期间经过了多少时间;其他答案都说了,并且已经举例了,我就不多说了。
如果您想对几条指令进行基准测试,这是一个很好的解决方案;例如,比较两种类型的函数——最好进行数千次,以确保对任何“扰动元素”进行平均。
像这样,如果你想知道序列化一个数组需要多长时间:
$before = microtime(true);
for ($i=0 ; $i<100000 ; $i++) {
serialize($list);
}
$after = microtime(true);
echo ($after-$before)/$i . " sec/serialize\n";
虽然不完美,但很有用,而且设置起来并不需要太多时间。
如果您想确定哪个函数在整个脚本中花费大量时间,另一个解决方案非常有效,那就是使用:
- The Xdebug http://xdebug.org/扩展,为脚本生成分析数据
- Software that read the profiling data, and presents you something readable. I know three of those :
-
Webgrind https://github.com/jokkedk/webgrind;网页界面;应该适用于任何 Apache+PHP 服务器
-
WinCacheGrind http://sourceforge.net/projects/wincachegrind/;仅在 Windows 上
-
K缓存研磨 https://kcachegrind.github.io/html/Home.html;可能只有 Linux 和 linux-like ;这是我更喜欢的,顺便说一句
要获取分析文件,您必须安装并配置 Xdebug ;看看分析 PHP 脚本 http://xdebug.org/docs/profiler文档的页面。
我通常做的是默认情况下不启用探查器(它会生成相当大的文件,并减慢速度),但可以发送一个名为XDEBUG_PROFILE
作为 GET 数据,仅激活我需要的页面的分析。
我的 php.ini 中与分析相关的部分如下所示:
xdebug.profiler_enable = 0 ; Profiling not activated by default
xdebug.profiler_enable_trigger = 1 ; Profiling activated when requested by the GET parameter
xdebug.profiler_output_dir = /tmp/ouput_directory
xdebug.profiler_output_name = files_names
(阅读文档以获取更多信息)
This screenshot is from a C++ program in KcacheGrind :
(source: sourceforge.net http://kcachegrind.sourceforge.net/html/pics/KcgShot3Large.gif)
You'll get exactly the same kind of thing with PHP scripts ;-)
(With KCacheGrind, I mean ; WinCacheGrind is not as good as KCacheGrind...)
这使您可以很好地了解应用程序中哪些内容花费了时间——有时它确实有助于定位the减慢一切的功能^^
请注意,Xdebug 会计算 PHP 所花费的 CPU 时间;当 PHP 等待数据库的答复时(例如),它不起作用;只能等待。所以Xdebug会认为DB请求不需要太多时间!
这应该在 SQL 服务器上进行分析,而不是 PHP,所以......
希望这有帮助:-)
玩得开心 !