Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to find PHP execution time?
In PHP, you can measure script execution time using several methods. The most common approaches include microtime() for simple timing and getrusage() for detailed CPU usage statistics.
Using microtime()
The simplest method to measure execution time uses microtime(true) to get timestamps ?
<?php
$start_time = microtime(true);
// Simulate some processing
for ($i = 0; $i < 1000000; $i++) {
$result = $i * 2;
}
$end_time = microtime(true);
$execution_time = $end_time - $start_time;
echo "Script execution time: " . number_format($execution_time, 6) . " seconds<br>";
echo "In milliseconds: " . number_format($execution_time * 1000, 3) . " ms";
?>
Script execution time: 0.023456 seconds In milliseconds: 23.456 ms
Using getrusage()
For detailed CPU usage statistics, getrusage() provides user time and system time separately ?
<?php
// Beginning of the script
$exec_start = getrusage();
// Simulate some processing
for ($i = 0; $i < 500000; $i++) {
$result = sqrt($i);
}
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 "The process used " . rutime($ru, $exec_start, "utime") .
" ms for the computations<br>";
echo "Spent " . rutime($ru, $exec_start, "stime") .
" ms during system calls<br>";
?>
The process used 15.625 ms for the computations Spent 0.312 ms during system calls
Comparison
| Method | Measures | Best For |
|---|---|---|
microtime() |
Wall clock time | Total script duration |
getrusage() |
CPU user/system time | CPU usage analysis |
Note − There is no need to calculate time difference if a PHP instance is spawned for every test.
Conclusion
Use microtime(true) for simple execution timing and getrusage() when you need detailed CPU usage statistics. The microtime() method is simpler and sufficient for most performance monitoring needs.
Advertisements
