如何找出在PHP脚本中花费的时间?

时间:2011-05-28 15:09:38

标签: php

我正在执行一个大约需要一分钟才能完成的PHP脚本,虽然默认时间限制设置为30秒,但脚本会在该限制之后继续执行。
我发现,限制只会影响脚本本身所花费的时间,而不会影响数据库查询等库函数所花费的时间。

有没有办法找出实际花费在里面脚本的时间?我试图使用getrusage,但它似乎没有为这个问题返回适当的值。

示例:

<?php
$time = microtime(TRUE);
sleep(100);
echo 'Time: ', microtime(TRUE) - $time;
?>

脚本等待100秒,并且在30秒的时间限制后不会终止。 根据set_time_limit的文档,在 sleep 函数内花费的时间(100秒)不参与计算执行时间,因为它是一个外部(库)函数。

5 个答案:

答案 0 :(得分:7)

I just want to know how much of the execution time is spent inside my script and how much is spent in library functions.

使用XDebug Profiler

答案 1 :(得分:5)

我猜你想要这样的东西:

<?php
// the whole operation
$time1 = time();

// perform some functions
$s = file_get_contents("somefilename");
$time2 = time();

// perform some library functions
$rs = some_third_party_library_function();
$time3 = time();

// Show results
echo "Overall Time spent: " . ($time3 - $time1) . "ms <br>";
echo "Time spent reading file: ". ($time2 - $time1) . "ms <br>";
echo "Time spent by Third Party Library: "  . ($time3 - $time2) . "ms <br>";
?>

希望这会有所帮助......

答案 2 :(得分:1)

您可以在输入脚本之前标记开始时间,然后在脚本结束后标记结束时间。然后回应差异。

<?php
$a=time();
sleep(5);
$b=time();
echo $b-$a;
?>

答案 3 :(得分:1)

如果需要测量单个函数与标准或内置PHP函数的执行时间,最好使用适当的调试器和代码分析器。 Xdebug正是这样做的。

答案 4 :(得分:0)

不知道您的脚本有多复杂,但您可以只为所有库函数调用添加注释。如果您的代码需要返回值才能正确执行,请将它们替换为常量值(可能已由这些函数返回)。例如:

$result = mysql_query( ... )

替换为:

// $result = mysql_query( ... )
$result = // resource, boolean or whatever you want   

然后运行脚本并使用Coding-Freak的建议计算执行时间。

如果您更喜欢Rio Bautista的方法,您可能会发现一些计算部分时间的函数。