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.
Clock time can get using microtime() function. First use it before starts the script and then at the end of the script. Then using formula (End_time – Start_time). The mirotime() function returns time in seconds.
Remember, the max execution time of a PHP script is 30 seconds.
max_execution_time int. This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30 . When running PHP from the command line the default setting is 0 .
The default execution time is 30 seconds, which may be too small for your needs. If you need to raise this limit, you must create a phprc file.
If all you need is the wall-clock time, rather than the CPU execution time, then it is simple to calculate:
//place this before any script you want to calculate time $time_start = microtime(true); //sample script for($i=0; $i<1000; $i++){ //do anything } $time_end = microtime(true); //dividing with 60 will give the execution time in minutes otherwise seconds $execution_time = ($time_end - $time_start)/60; //execution time of the script echo '<b>Total Execution Time:</b> '.$execution_time.' Mins'; // if you get weird results, use number_format((float) $execution_time, 10)
Note that this will include the time that PHP is sat waiting for external resources such as disks or databases, which is not used for max_execution_time
.
On unixoid systems (and in php 7+ 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With