Wednesday, September 12, 2012

How to calculate CPU usage of a PHP script


There are many PHP scripts that calculate it’s execution time, memory usage and even the number of queries sent to databases.

All of these indicators are extremely important when testing the code to optimize it later. For me, however, there is still one parameter missing: the percentage of time the processor spends on execution of the PHP script itself!

Solution
In most cases, the calculation is very simple. Just use the built-in getrusage() function:


function onRequestStart() {
 $dat = getrusage();
 define('PHP_TUSAGE', microtime(true));
 define('PHP_RUSAGE', $dat["ru_utime.tv_sec"]*1e6+$dat["ru_utime.tv_usec"]);
}

function getCpuUsage() {
    $dat = getrusage();
    $dat["ru_utime.tv_usec"] = ($dat["ru_utime.tv_sec"]*1e6 + $dat["ru_utime.tv_usec"]) - PHP_RUSAGE;
    $time = (microtime(true) - PHP_TUSAGE) * 1000000;

    // cpu per request
    if($time > 0) {
        $cpu = sprintf("%01.2f", ($dat["ru_utime.tv_usec"] / $time) * 100);
    } else {
        $cpu = '0.00';
    }

    return $cpu;
}

?>

Instruction for this script is fairly simple. You have to call the onRequestStart() function during the start of application. Then later in the code you can call the getCpuUsage() function any time you want to get the current CPU usage of your program (preferably you should do this by the end of the script).
Source : http://php.webtutor.pl/en/2011/05/13/how-to-calculate-cpu-usage-of-a-php-script/

No comments:

Post a Comment