How to calculate real CPU usage in a PHP script
Simple function you need to add to begin is the following. This will let us compute the results. ``` 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)); } ``` Now we just add the following before the code we want to get real CPU usage on. ``` $cpu_before = getrusage(); ``` Now just after all your code add the following, feel free to edit as needed. What this will do is output the CPU time on the page. ``` $cpu_after = getrusage(); echo "<div>Took ".rutime($cpu_after, $cpu_before, "utime")." ms CPU usage</div>"; ``` This is a simple code for checking CPU usage I use all the time to see if my code is slow for CPU working reasons, or because of API calls or other stuff. This is real CPU usage and NOT time it took to run, you can get a result of 33ms and the script can take 40 seconds if it's just waiting for content from things like an API requests or a database that is way to slow.