twk twk - 1 year ago 79
PHP Question

Tracking the script execution time in PHP

PHP must track the amount of CPU time a particular script has used in order to enforce the max_execution_time limit.

Is there a way to get access to this inside of the script? I'd like to include some logging with my tests about how much CPU was burnt in the actual PHP (the time is not incremented when the script is sitting and waiting for the database).

I am using a Linux box.

Answer Source

On unixoid systems (and in php 7.0.0 on Windows as well), you can use getrusage, like:

// Script start
$rustart = getrusage();

// Code ...

// Script end
function rutime($ru, $rus, $index) {
    return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
     -  ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));

$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
    " ms for its computations\n";
echo "It spent " . rutime($ru, $rustart, "stime") .
    " ms in system calls\n";

Note that you don't need to calculate a difference if you are spawning a php instance for every test.