How to Monitor Script Execution Time in PHP with Precision
Maintaining strict control over a script's execution time is crucial in adhering to the max_execution_time limit imposed by PHP. However, obtaining access to this information from within the script itself can be advantageous, especially for logging and analysis purposes.
For developers working in a Linux environment, PHP offers a straightforward approach to track the wall-clock time. By employing the microtime() function, it becomes possible to determine the script's elapsed time precisely.
To implement this technique, simply incorporate the following lines of code at the beginning of the script you wish to track:
$time_start = microtime(true);
Following the desired script execution, insert these lines to capture the end time:
$time_end = microtime(true);
To calculate the execution time, subtract the start time from the end time and divide the result by the desired unit. For instance, to obtain the execution time in minutes, the following formula can be used:
$execution_time = ($time_end - $time_start) / 60;
Echoing the $execution_time variable will display the total execution time. It's noteworthy that this method measures the elapsed time, including any periods when the script is waiting for external resources.
For developers seeking a precise indicator of CPU usage, it's important to note that the wall-clock time method outlined here does not provide that information. In PHP, the CPU execution time cannot be directly obtained from within the script.
The above is the detailed content of How Can I Precisely Monitor PHP Script Execution Time?. For more information, please follow other related articles on the PHP Chinese website!