开发者

How to find out the time spent inside a PHP script?

I'm executing a PHP script that takes about a minute to finish and although the default time limit is set to 30 seconds, the script continues its execution after that limit.

I found out, that the limit only affects the time that is开发者_开发知识库 spent inside the script itself and not the time spent in library functions like database queries etc.

Is there a way to find out the time that is actually spent inside the script? I tried to use getrusage, but it doesn't seem to return the appropriate values for this problem.

Example:

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

The script waits for 100 seconds and does not terminate after the time limit of 30 seconds. According to the documentation of set_time_limit, the time that is spent inside the sleep function (100 seconds) is not involved in the calculation of the execution time, because it's an external (library) function.


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

Use XDebug Profiler for it.


I'm guessing you want something like this:

<?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) . "s <br>";
echo "Time spent reading file: ". ($time2 - $time1) . "s <br>";
echo "Time spent by Third Party Library: "  . ($time3 - $time2) . "s <br>";
?>


You can mark the start time before entering the script, then mark the end time after the script ends. Echo the difference then.

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


If you need to measure the execution time of individual functions vs standard or built-in PHP functions, this is best done with a proper debugger and code profiler. Xdebug does exactly that.


Don't know how complicated your script is, however you can just add a comment to all your library functions calls. If your code requires their returned values in order to be properly executed, replace them with constant values (that could have been returned by these functions). For example:

$result = mysql_query( ... )

replace with:

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

Then run the script and calculate the execution time using Coding-Freak's suggestion.

If you prefer Rio Bautista's approach you may find some functions that calculates section's time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜