Home >Backend Development >PHP Tutorial >How Can I Precisely Measure PHP Script Execution Time for Performance Monitoring?
Obtaining Script Execution Time in PHP for Precise Logging
The PHP interpreter tracks CPU utilization to adhere to the max_execution_time limit. While this mechanism is essential for safeguarding against infinite loops and resource exhaustion, it can also be useful for developers to monitor script performance.
To access this information during script execution, the Linux-based command "microtime(true)" provides the current timestamp. By recording the timestamp before and after the desired code snippet, the execution time can be calculated.
// Track start time before executing the code $time_start = microtime(true); // Insert your code here // Record end time after executing the code $time_end = microtime(true); // Calculate execution time (in seconds) $execution_time = $time_end - $time_start;
It's important to note that this method measures wall-clock time rather than pure CPU time. Therefore, it includes the time spent waiting for external resources like databases, which is not relevant to the max_execution_time limit.
// Display the formatted execution time echo "Execution Time: " . number_format($execution_time, 5) . " seconds";
By leveraging this technique, developers can incorporate more detailed logging into their tests and gain insights into the actual CPU utilization of their scripts.
The above is the detailed content of How Can I Precisely Measure PHP Script Execution Time for Performance Monitoring?. For more information, please follow other related articles on the PHP Chinese website!