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.
The cheapest and dirtiest way to do it is simply make
microtime()
calls at places in your code you want to benchmark. Do it right before and right after database queries and it's simple to remove those durations from the rest of your script execution time.A hint: your PHP execution time is rarely going to be the thing that makes your script timeout. If a script times out it's almost always going to be a call to an external resource.
PHP microtime documentation: http://us.php.net/microtime
If all you need is the wall-clock time, rather than the CPU execution time, then it is simple to calculate:
Note that this will include time that PHP is sat waiting for external resources such as disks or databases, which is not used for max_execution_time.
I created an ExecutionTime class out of phihag answer that you can use out of box:
usage:
On unixoid systems (and in php 7+ on Windows as well), you can use getrusage, like:
Note that you don't need to calculate a difference if you are spawning a php instance for every test.
It is going to be prettier if you format the seconds output like:
will print
This is much better than